Ejemplo n.º 1
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>
        /// <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(ondataheader);

            //Initialize dates
            SetStartDate(2013, 10, 07);
            SetEndDate(2013, 10, 07);
            SetCash(25000);

            //Add as many securities as you like. All the data will be passed into the event handler:
            AddSecurity(SecurityType.Equity, _symbol, Resolution.Minute);

            maxHigh = new Maximum("MaxHigh", _period);
            minLow = new Minimum("MinLow", _period);
            value1 = new RollingWindow<IndicatorDataPoint>(_period);
            fish = new RollingWindow<IndicatorDataPoint>(_period);
            //wma = new LinearWeightedMovingAverage(5);       // induces 2 bar lag
            //wwma = new RollingWindow<IndicatorDataPoint>(_period);
            //fishHigh = new Maximum("FishHigh", 400);
            //fishLow = new Minimum("FishLow", 400);
            fx = new FisherTransform(_symbol,_period);
            //fx = FT(_symbol, _period, Resolution.Minute);

            // Add a bars to initialize the RollingWindow
            value1.Add(new IndicatorDataPoint(DateTime.MinValue, .0001m));
            value1.Add(new IndicatorDataPoint(DateTime.MinValue, .0001m));
            fish.Add(new IndicatorDataPoint(DateTime.MinValue, 0m));
            fish.Add(new IndicatorDataPoint(DateTime.MinValue, 0m));
            //wwma.Add(new IndicatorDataPoint(DateTime.MinValue, .0001m));
            //wwma.Add(new IndicatorDataPoint(DateTime.MinValue, .0001m));
        }
Ejemplo n.º 2
0
        public void ComputesCorrectly()
        {
            var max = new Maximum(3);

            var reference = DateTime.MinValue;

            max.Update(reference.AddDays(1), 1m);
            Assert.AreEqual(1m, max.Current.Value);
            Assert.AreEqual(0, max.PeriodsSinceMaximum);

            max.Update(reference.AddDays(2), -1m);
            Assert.AreEqual(1m, max.Current.Value);
            Assert.AreEqual(1, max.PeriodsSinceMaximum);

            max.Update(reference.AddDays(3), 0m);
            Assert.AreEqual(1m, max.Current.Value);
            Assert.AreEqual(2, max.PeriodsSinceMaximum);

            max.Update(reference.AddDays(4), -2m);
            Assert.AreEqual(1m, max.Current.Value);
            Assert.AreEqual(3, max.PeriodsSinceMaximum);

            max.Update(reference.AddDays(5), -2m);
            Assert.AreEqual(0m, max.Current.Value);
            Assert.AreEqual(2, max.PeriodsSinceMaximum);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Creates a new Stochastics Indicator from the specified periods.
        /// </summary>
        /// <param name="name">The name of this indicator.</param>
        /// <param name="period">The period given to calculate the Fast %K</param>
        /// <param name="kPeriod">The K period given to calculated the Slow %K</param>
        /// <param name="dPeriod">The D period given to calculated the Slow %D</param>
        public Stochastic(string name, int period, int kPeriod, int dPeriod)
            : base(name)
        {
            Maximum = new Maximum(name + "_Max", period);
            Mininum = new Minimum(name + "_Min", period);
            SumFastK = new Sum(name + "_SumFastK", kPeriod);
            SumSlowK = new Sum(name + "_SumD", dPeriod);

            FastStoch = new FunctionalIndicator<TradeBar>(name + "_FastStoch",
                input => ComputeFastStoch(period, input),
                fastStoch => Maximum.IsReady,
                () => Maximum.Reset()
                );

            StochK = new FunctionalIndicator<TradeBar>(name + "_StochK",
                input => ComputeStochK(period, kPeriod, input),
                stochK => Maximum.IsReady,
                () => Maximum.Reset()
                );

            StochD = new FunctionalIndicator<TradeBar>(name + "_StochD",
                input => ComputeStochD(period, kPeriod, dPeriod),
                stochD => Maximum.IsReady,
                () => Maximum.Reset()
                );
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MidPrice"/> class using the specified name and period.
 /// </summary> 
 /// <param name="name">The name of this indicator</param>
 /// <param name="period">The period of the MIDPRICE</param>
 public MidPrice(string name, int period) 
     : base(name)
 {
     _period = period;
     _maximum = new Maximum(period);
     _minimum = new Minimum(period);
 }
Ejemplo n.º 5
0
        public void ComputesCorrectly2()
        {
            const int period = 5;
            var max = new Maximum(period);

            Assert.AreEqual(0m, max.Current.Value);

            // test an increasing stream of data
            for (int i = 0; i < period; i++)
            {
                max.Update(DateTime.Now.AddDays(1), i);
                Assert.AreEqual(i, max.Current.Value);
                Assert.AreEqual(0, max.PeriodsSinceMaximum);
            }

            // test a decreasing stream of data
            for (int i = 0; i <= period; i++)
            {
                max.Update(DateTime.Now.AddDays(period + i), period - i - 1);
                Assert.AreEqual(period - 1, max.Current.Value);
                Assert.AreEqual(i, max.PeriodsSinceMaximum);
            }

            Assert.AreEqual(max.Period, max.PeriodsSinceMaximum);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// A Fisher Transform of Prices
        /// </summary>
        /// <param name="name">string - the name of the indicator</param>
        /// <param name="period">The number of periods for the indicator</param>
        public FisherTransform(string name, int period)
            : base(name)
        {
            _alpha = .33;

            // Initialize the local variables
            _medianMax = new Maximum("MedianMax", period);
            _medianMin = new Minimum("MedianMin", period);
        }
Ejemplo n.º 7
0
        private void TextBox_LostFocus(object Sender, RoutedEventArgs E)
        {
            if (!IsNumeric)
            {
                return;
            }

            double floatValue;
            bool   badEntry;

            if (String.IsNullOrWhiteSpace(Text))
            {
                Text = m_OldText;
            }

            if (IsFloat)
            {
                badEntry =
                    !double.TryParse(Text, NumberStyles.Number | NumberStyles.AllowDecimalPoint,
                                     CultureInfo.InvariantCulture, out floatValue);
            }
            else
            {
                int value;

                badEntry =
                    !int.TryParse(Text, NumberStyles.Number | NumberStyles.AllowDecimalPoint,
                                  CultureInfo.InvariantCulture, out value);
                floatValue = value;
            }

            if (!badEntry)
            {
                if (floatValue > Maximum)
                {
                    Text = Maximum.ToString(CultureInfo.InvariantCulture);
                    Select(Text.Length, 0);
                }
                else if (floatValue < Minimum)
                {
                    Text = Minimum.ToString(CultureInfo.InvariantCulture);
                    Select(Text.Length, 0);
                }
                else
                {
                    Text = floatValue.ToString(CultureInfo.InvariantCulture);
                    Select(Text.Length, 0);
                }
            }
            else
            {
                Text = m_OldText;
            }
        }
Ejemplo n.º 8
0
        public string ToString(string format)
        {
            var value = (Minimum == DateTime.MinValue ? String.Empty : Minimum.ToString(format)) + "-"
                        + (Maximum == DateTime.MaxValue ? String.Empty : Maximum.ToString(format));

            if (value == "-")
            {
                return(String.Empty);
            }
            return(value);
        }
Ejemplo n.º 9
0
        private SizeF LabelSize(Graphics g)
        {
            SizeF v      = g.MeasureString(Value.ToString(_numberFormat), Font);
            SizeF max    = g.MeasureString(Maximum.ToString(_numberFormat), Font);
            SizeF min    = g.MeasureString(Maximum.ToString(_numberFormat), Font);
            SizeF result = v;

            result.Height = Math.Max(Math.Max(v.Height, max.Height), min.Height);
            result.Width  = Math.Max(Math.Max(v.Width, max.Width), min.Width);
            return(result);
        }
Ejemplo n.º 10
0
        protected override double Execute(IGameState gameState)
        {
            var min = Minimum.Evaluate(gameState);
            var max = Maximum.Evaluate(gameState);

            if (Condition.Evaluate(gameState))
            {
                _value = (_random.NextDouble() * (max - min) + min);
            }

            return(_value);
        }
Ejemplo n.º 11
0
        public void ResetsProperly()
        {
            var max = new Maximum(3);
            max.Update(DateTime.Today, 1m);
            max.Update(DateTime.Today.AddSeconds(1), 2m);
            max.Update(DateTime.Today.AddSeconds(2), 1m);
            Assert.IsTrue(max.IsReady);

            max.Reset();
            Assert.AreEqual(0, max.PeriodsSinceMaximum);
            TestHelper.AssertIndicatorIsInDefaultState(max);
        }
Ejemplo n.º 12
0
 public bool Equals(Value other)
 {
     if (ReferenceEquals(null, other))
     {
         return(false);
     }
     if (ReferenceEquals(this, other))
     {
         return(true);
     }
     return(Maximum.Equals(other.Maximum) && Actual.Equals(other.Actual));
 }
Ejemplo n.º 13
0
 /// <summary>
 /// Serializes content to the writer
 /// </summary>
 public void ToBinary(IBinaryRawWriter writer)
 {
     writer.WriteDouble(Station);
     writer.WriteInt(Offsets.Count);
     foreach (var offset in Offsets)
     {
         offset.ToBinary(writer);
     }
     Minimum.ToBinary(writer);
     Maximum.ToBinary(writer);
     Average.ToBinary(writer);
 }
Ejemplo n.º 14
0
 public override int GetHashCode()
 {
     unchecked
     {
         int hash = 17;
         hash = hash * 29 + Minimum.GetHashCode();
         hash = hash * 29 + Maximum.GetHashCode();
         hash = hash * 29 + IsMinimumOpen.GetHashCode();
         hash = hash * 29 + IsMaximumOpen.GetHashCode();
         return(hash);
     }
 }
Ejemplo n.º 15
0
 public void Write(BinaryWriter writer)
 {
     writer.Write(Station);
     writer.Write(Offsets.Count);
     foreach (var offset in Offsets)
     {
         offset.Write(writer);
     }
     Minimum.Write(writer);
     Maximum.Write(writer);
     Average.Write(writer);
 }
Ejemplo n.º 16
0
        protected override void OnRender(int x, int y, int width, int height)
        {
            _btnW = System.Math.Max(_font.CharWidth('-'), _font.CharWidth('+')) + 8;
            int txtY = _h / 2 - _font.Height / 2;

            // Draw Shadow
            Core.Screen.DrawRectangle(Colors.White, 1, Left + 1, Top + 1, Width - 1, Height - 1, 1, 1, 0, 0, 0, 0, 0, 0, 0);

            // Draw Border
            Core.Screen.DrawRectangle((Focused) ? Core.SystemColors.SelectionColor : Core.SystemColors.BorderColor, 1,
                                      Left, Top, Width - 1, Height - 1, 1, 1, 0, 0, 0, 0, 0, 0, 0);

            // Draw Minus Button
            if (Enabled)
            {
                Core.Screen.DrawRectangle(0, 0, Left + 1, Top + 1, _btnW, Height - 3, 0, 0, _btnTop, Left, Top, _btnBtm, Left, Top + Height, 256);
                Core.Screen.DrawTextInRect("-", Left + 2, Top + txtY + 1, _btnW, _font.Height, Bitmap.DT_AlignmentCenter, _btnTxtShd, _font);
            }
            else
            {
                Core.Screen.DrawRectangle(0, 0, Left + 1, Top + 1, _btnW, Height - 3, 0, 0, _btnTop, Left, Top, _btnTop, Left, Top + Height, 256);
            }
            Core.Screen.DrawTextInRect("-", Left + 1, Top + txtY, _btnW, _font.Height, Bitmap.DT_AlignmentCenter, _btnTxt, _font);

            // Draw Number
            Core.Screen.DrawRectangle((Focused) ? Core.SystemColors.SelectionColor : Core.SystemColors.BorderColor, 1,
                                      Left + _btnW + 1, Top, Width - _btnW - _btnW - 3, Height - 1, 0, 0, _bkgTop, Left, Top, (Enabled) ? _bkgBtm : _bkgTop,
                                      Left, Top + Height, 256);
            Core.Screen.DrawTextInRect(IntToNString(Value, Maximum.ToString().Length), Left + _btnW + 4, Top + txtY,
                                       Width - _btnW - _btnW - 9, Height - 1, Bitmap.DT_AlignmentRight, (Enabled) ? _fore : _disabled, _font);

            // Draw Minus Button
            Core.Screen.DrawRectangle(0, 0, Left + Width - _btnW - 2, Top + 1, _btnW, Height - 3, 0, 0, _btnTop, Left, Top,
                                      (Enabled) ? _btnBtm : _btnTop, Left, Top + Height, 256);
            if (Enabled)
            {
                Core.Screen.DrawTextInRect("+", Left + Width - _btnW - 1, Top + txtY + 1, _btnW, _font.Height, Bitmap.DT_AlignmentCenter,
                                           _btnTxtShd, _font);
            }
            Core.Screen.DrawTextInRect("+", Left + Width - _btnW - 2, Top + txtY, _btnW, _font.Height, Bitmap.DT_AlignmentCenter, _btnTxt, _font);

            if (Focused)
            {
                Core.Screen.DrawRectangle(0, 0, x + 1, y + 1, width - 3, 1, 0, 0, Core.SystemColors.SelectionColor, 0, 0, Core.SystemColors.SelectionColor, 0, 0, 90);
                Core.Screen.DrawRectangle(0, 0, x + 1, y + height - 3, width - 3, 1, 0, 0, Core.SystemColors.SelectionColor, 0, 0, Core.SystemColors.SelectionColor, 0, 0, 90);
                Core.Screen.DrawRectangle(0, 0, x + 1, y + 2, 1, height - 5, 0, 0, Core.SystemColors.SelectionColor, 0, 0, Core.SystemColors.SelectionColor, 0, 0, 90);
                Core.Screen.DrawRectangle(0, 0, x + width - 3, y + 2, 1, height - 5, 0, 0, Core.SystemColors.SelectionColor, 0, 0, Core.SystemColors.SelectionColor, 0, 0, 90);
                Core.Screen.DrawRectangle(0, 0, x + 2, y + 2, width - 5, 1, 0, 0, Core.SystemColors.SelectionColor, 0, 0, Core.SystemColors.SelectionColor, 0, 0, 40);
                Core.Screen.DrawRectangle(0, 0, x + 2, y + height - 4, width - 5, 1, 0, 0, Core.SystemColors.SelectionColor, 0, 0, Core.SystemColors.SelectionColor, 0, 0, 40);
                Core.Screen.DrawRectangle(0, 0, x + 2, y + 4, 1, height - 7, 0, 0, Core.SystemColors.SelectionColor, 0, 0, Core.SystemColors.SelectionColor, 0, 0, 40);
                Core.Screen.DrawRectangle(0, 0, x + width - 4, y + 3, 1, height - 7, 0, 0, Core.SystemColors.SelectionColor, 0, 0, Core.SystemColors.SelectionColor, 0, 0, 40);
            }
        }
Ejemplo n.º 17
0
 public int CompareTo(T item)
 {
     if (Minimum.CompareTo(item) > 0)
     {
         return(-1);
     }
     if (Maximum.CompareTo(item) < 0)
     {
         return(1);
     }
     return(0);
 }
Ejemplo n.º 18
0
        public void RecordAllTimeHighEvent(Symbol symbol, int period, Resolution?res, Func <IBaseData, decimal> selectorHigh = null, Func <IBaseData, decimal> selectorLowOfHigh = null)
        {
            Maximum        allTimeHigh       = SetAllTimeHigh(symbol, period, res, selectorHigh);
            Maximum        allTimeHighLow    = SetAllTimeHighLow(symbol, period, res, selectorLowOfHigh);
            HistoricalHigh newHistoricalHigh = new HistoricalHigh();

            newHistoricalHigh.ath   = allTimeHigh;
            newHistoricalHigh.aLth  = allTimeHighLow;
            newHistoricalHigh.count = historicalHighs.Count;


            historicalHighs.Add(newHistoricalHigh);
        }
Ejemplo n.º 19
0
        public void ResetsProperlyMaximum()
        {
            var max = new Maximum(3);

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

            max.Reset();
            Assert.AreEqual(0, max.PeriodsSinceMaximum);
            TestHelper.AssertIndicatorIsInDefaultState(max);
        }
Ejemplo n.º 20
0
        public Maximum MAX(Symbol symbol, int period, TimeSpan interval, Func <TradeBar, decimal> selector = null)
        {
            var max = new Maximum(symbol.ToString() + "_MAX_" + period + "_" + interval.ToString(), period);

            // assign a default value for the selector function
            if (selector == null)
            {
                selector = x => x.High;
            }

            RegisterIndicator(symbol, max, interval, selector);
            return(max);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Indicates whether this instance and a specified envelope are equal.
        /// </summary>
        /// <param name="another">The envelope to compare with this instance.</param>
        /// <returns><c>true</c> if <paramref name="another" /> and this instance represent the same value; otherwise, <c>false</c>.</returns>
        public Boolean Equals(Envelope another)
        {
            if (ReferenceEquals(null, another))
            {
                return(false);
            }
            if (ReferenceEquals(this, another))
            {
                return(true);
            }

            return(Minimum.Equals(another.Minimum) && Maximum.Equals(another.Maximum));
        }
Ejemplo n.º 22
0
        private Layer ConvertMaximum(tflite.Operator op)
        {
            var inputs = op.GetInputsArray();
            var inputA = _graph.Tensors(inputs[0]).Value;
            var inputB = _graph.Tensors(inputs[1]).Value;

            var layer = new Maximum(inputA.GetShapeArray().ToNCHW(), inputB.GetShapeArray().ToNCHW());

            _inputs.Add(layer.InputA, inputs[0]);
            _inputs.Add(layer.InputB, inputs[1]);
            _outputs.Add(op.Outputs(0), layer.Output);
            return(layer);
        }
Ejemplo n.º 23
0
        private void CopyTo(Movement r, int cloneFlags)
        {
            r.easing_ = easing_?.Clone(cloneFlags);

            if (!Bits.IsSet(cloneFlags, Utilities.CloneZero))
            {
                r.Minimum = Minimum?.Clone(cloneFlags);
                r.Maximum = Maximum?.Clone(cloneFlags);
            }

            r.magnitude_ = 0;
            r.forwards_  = true;
        }
Ejemplo n.º 24
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>
        /// <seealso cref="QCAlgorithm.SetStartDate(System.DateTime)"/>
        /// <seealso cref="QCAlgorithm.SetEndDate(System.DateTime)"/>
        /// <seealso cref="QCAlgorithm.SetCash(decimal)"/>
        public override void Initialize()
        {
            //Initialize dates
            SetStartDate(2015, 6, 15);
            SetEndDate(2015, 6, 15);
            SetCash(25000);

            //Add as many securities as you like. All the data will be passed into the event handler:
            AddSecurity(SecurityType.Equity, symbol, Resolution.Minute);
            #region "Init indicators"
            Price                 = new RollingWindow <IndicatorDataPoint>(samplesize);
            ema                   = new RollingWindow <IndicatorDataPoint>(samplesize);
            zema                  = new RollingWindow <IndicatorDataPoint>(samplesize);
            OptimalValue1         = new RollingWindow <IndicatorDataPoint>(samplesize);
            OmtimalValue2         = new RollingWindow <IndicatorDataPoint>(samplesize);
            OptimalTrackingFilter = new RollingWindow <IndicatorDataPoint>(samplesize);
            lambda                = new RollingWindow <IndicatorDataPoint>(samplesize);
            alpha                 = new RollingWindow <IndicatorDataPoint>(samplesize);
            priceOptimalDiff      = new RollingWindow <IndicatorDataPoint>(samplesize);
            priceOptimalSign      = new RollingWindow <IndicatorDataPoint>(samplesize);
            priceOptimalCross     = new RollingWindow <IndicatorDataPoint>(samplesize);
            fudge                 = new RollingWindow <IndicatorDataPoint>(samplesize);
            instantTrend          = new RollingWindow <IndicatorDataPoint>(samplesize);
            instantTrendTrigger   = new RollingWindow <IndicatorDataPoint>(samplesize);
            cyberCycle            = new RollingWindow <IndicatorDataPoint>(samplesize);
            centerGravity         = new RollingWindow <IndicatorDataPoint>(samplesize);
            cyberCycleSmooth      = new RollingWindow <IndicatorDataPoint>(samplesize);
            rvi                   = new RelativeVigorIndex(8);
            rviHistory            = new RollingWindow <IndicatorDataPoint>(samplesize);

            stochCenterGravityValue1 = new RollingWindow <IndicatorDataPoint>(8);
            stochCenterGravityValue2 = new RollingWindow <IndicatorDataPoint>(8);

            stochCyberCycleValue1        = new RollingWindow <IndicatorDataPoint>(8);
            stochCyberCycleValue2        = new RollingWindow <IndicatorDataPoint>(8);
            stochCyberCycleInverseFisher = new RollingWindow <IndicatorDataPoint>(8);
            stochCyberCycleFisher        = new RollingWindow <IndicatorDataPoint>(8);

            stochRviHistoryValue1 = new RollingWindow <IndicatorDataPoint>(8);
            stochRviHistoryValue2 = new RollingWindow <IndicatorDataPoint>(8);

            ROC           = new RateOfChange(4);
            maxCyberCycle = new Maximum(8);
            minCyberCycle = new Minimum(8);
            #endregion
            //mylog.Debug(transheader);
            mylog.Debug(ondataheader);
            string msg = "Security,Date,Day Profit,Day Fees, Day Net, Total Profit, Total Fees";
            mylog.Debug(msg);
            mylog.Debug(tradeheader);
        }
Ejemplo n.º 25
0
            }                                                        //最近成交价

            public SymbolData(Symbol symbol, Turtle algorithm)
            {
                Symbol        = symbol;
                Security      = algorithm.Securities[symbol];
                Position      = 0;
                LastFillPrice = -1;

                Close = algorithm.Identity(symbol);
                EMA   = algorithm.EMA(symbol, NUMDAYAVG, TimeSpan.FromDays(1));
                MAX   = algorithm.MAX(symbol, NUMDAYMAX, TimeSpan.FromDays(1));
                MIN   = algorithm.MIN(symbol, NUMDAYMIN, TimeSpan.FromDays(1));

                _algorithm = algorithm;
            }
Ejemplo n.º 26
0
        public override bool Equals(object other)
        {
            if (other == null)
            {
                return(false);
            }

            if (!(other is Interval))
            {
                return(false);
            }

            return(Minimum.Equals(((Interval)other).Minimum) && Maximum.Equals(((Interval)other).Maximum));
        }
Ejemplo n.º 27
0
        public override int GetHashCode()
        {
            int hashCode = 205049560;

            hashCode = hashCode * -1521134295 + Transform.GetHashCode();
            hashCode = hashCode * -1521134295 + Material.GetHashCode();
            hashCode = hashCode * -1521134295 + SavedRay.GetHashCode();
            hashCode = hashCode * -1521134295 + Parent.GetHashCode();
            hashCode = hashCode * -1521134295 + HasParent.GetHashCode();
            hashCode = hashCode * -1521134295 + Maximum.GetHashCode();
            hashCode = hashCode * -1521134295 + Minimum.GetHashCode();
            hashCode = hashCode * -1521134295 + Closed.GetHashCode();
            return(hashCode);
        }
Ejemplo n.º 28
0
        public void OnAllUpdatedOnce_Count2_Properties1()
        {
            var input = new Identity("Source");
            var max1  = new Maximum(3).Of(input);
            var max2  = new Maximum(3).Of(input);

            var a = Concat.OnAllUpdatedOnce(new IUpdatable[] { max1, max2 });


            input.Feed(10, 1, 0.1);

            a.Current.Count.Should().Be(2);
            a.Current.Properties.Should().Be(1);
        }
Ejemplo n.º 29
0
 /// <summary>
 /// Updates the maximum value in the range if the proposed value is greater than the current maximum value.
 /// </summary>
 /// <param name="proposedMax">New candidate value for the maximum.</param>
 public void UpdateMaximum(T proposedMax)
 {
     if (_maxValid)
     {
         if (Maximum.CompareTo(proposedMax) < 0)
         {
             Maximum = proposedMax;
         }
     }
     else
     {
         Maximum = proposedMax;
     }
 }
Ejemplo n.º 30
0
 protected override void UpdateElementsLayout()
 {
     _elems[0].Bounds = new Rectangle(0, 0, this.Width, SystemInformation.VerticalScrollBarWidth);
     _elems[1].Bounds = Rectangle.FromLTRB(0,
                                           this.Height - _elems[0].Bounds.Height, this.Width, this.Height);
     _elems[2].Bounds.Width = this.Width;
     using (Graphics gr = this.CreateGraphics()) {
         float height = Math.Max(
             gr.MeasureString(Maximum.ToString(), base.Font).Width,
             gr.MeasureString(Minimum.ToString(), base.Font).Width) + 4f;
         _elems[2].Bounds.Height = (int)height;
     }
     UpdateTrackerPosition();
 }
Ejemplo n.º 31
0
        /// <summary>
        /// Returns a string representation for this <see cref="CustomProgressBar" />.
        /// </summary>
        /// <returns>A <see cref="string" /> that describes this control.</returns>
        public override string ToString()
        {
            System.Text.StringBuilder builder = new System.Text.StringBuilder();

            builder.Append(GetType().FullName);
            builder.Append(", Minimum: ");
            builder.Append(Minimum.ToString(CultureInfo.CurrentCulture));
            builder.Append(", Maximum: ");
            builder.Append(Maximum.ToString(CultureInfo.CurrentCulture));
            builder.Append(", Value: ");
            builder.Append(Value.ToString(CultureInfo.CurrentCulture));

            return(builder.ToString());
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Creates a new AroonOscillator from the specified up/down periods.
        /// </summary>
        /// <param name="name">The name of this indicator</param>
        /// <param name="upPeriod">The lookback period to determine the highest high for the AroonDown</param>
        /// <param name="downPeriod">The lookback period to determine the lowest low for the AroonUp</param>
        public AroonOscillator(string name, int upPeriod, int downPeriod)
            : base(name)
        {
            var max = new Maximum(name + "_Max", upPeriod);
            AroonUp = new FunctionalIndicator<IndicatorDataPoint>(name + "_AroonUp",
                input => ComputeAroonUp(upPeriod, max, input),
                aroonUp => max.IsReady
                );

            var min = new Minimum(name + "_Min", downPeriod);
            AroonDown = new FunctionalIndicator<IndicatorDataPoint>(name + "_AroonDown",
                input => ComputeAroonDown(downPeriod, min, input),
                aroonDown => min.IsReady
                );
        }
        protected override void OnTextBoxTextChanged(object source, EventArgs e)
        {
            TextBox textBox = source as TextBox;
            int     val     = 0;

            NextDigitClears = false;
            if (int.TryParse(textBox.Text, out val))
            {
                textBox.Text = val.ToString("D" + Maximum.ToString().Length);
            }
            else
            {
                base.OnTextBoxTextChanged(source, e);
            }
        }
Ejemplo n.º 34
0
        public void UseCase1()
        {
            var input = new Identity("Source");
            var ema   = new ExponentialMovingAverage(12).Of(input);
            var max1  = new Maximum(6).Of(ema);
            var max2  = new Maximum(12).Of(ema);
            var max3  = new Maximum(24).Of(ema);

            var a             = Concat.OnAllUpdatedOnce(new IUpdatable[] { max1, max2 });
            var b             = Concat.OnAllUpdatedOnce(new IUpdatable[] { max2, max3, max3 });
            var finalCruncher = Concat.OnAllUpdatedOnce(new IUpdatable[] { a, b });

            input.FeedTradeBar(200, 1, 0.1);
            Console.WriteLine(finalCruncher.Samples);
        }
Ejemplo n.º 35
0
        public void OnAllUpdatedOnce_Count2_Properties5()
        {
            var input = new Identity("Source");
            var max1  = new Maximum(3).Of(input);
            var max2  = new Maximum(3).Of(input);

            var a  = Concat.OnAllUpdatedOnce(new IUpdatable[] { max1, max2 });
            var ba = Concat.OnAllUpdatedOnce(new IUpdatable[] { max1, max2, a }, name: "Target");

            input.FeedTradeBar(10, 1, 0.1);
            input.Update(ba.CurrentTime + 1000, 100d);
            ba.Current.Count.Should().Be(4);
            ba.Current.Properties.Should().Be(1);
            ba.Current.AsDoubleSpan.ToArray().Should().AllBeEquivalentTo(100d);
        }
 /// <summary>Value, Minimum, Maximum, SmallChange, LargeChange and TickFrequency are compared.</summary>
 public override bool Equals(object obj)
 {
     if (obj == null || (this.GetType() != obj.GetType()))
     {
         return(false);
     }
     try
     {
         var objAsT = (RangedRangeType <T>)obj;
         if (From.Equals(objAsT.From))
         {
             return(false);
         }
         if (To.Equals(objAsT.To))
         {
             return(false);
         }
         if (Minimum.Equals(objAsT.Minimum))
         {
             return(false);
         }
         if (Maximum.Equals(objAsT.Maximum))
         {
             return(false);
         }
         if (SmallChange.Equals(objAsT.SmallChange))
         {
             return(false);
         }
         if (LargeChange.Equals(objAsT.LargeChange))
         {
             return(false);
         }
         if (TickFrequency.Equals(objAsT.TickFrequency))
         {
             return(false);
         }
         return(true);
     }
     catch (Exception ex)
     {
         if (CanRaiseDebbugerBreak)
         {
             Debugger.Break(); Console.WriteLine(ex.Message);
         }
         return(false);
     }
 }
Ejemplo n.º 37
0
        public string ToString(IFormatProvider format)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("{0}: {1}\r\n", nameof(Minimum), Minimum.ToString(format));
            sb.AppendFormat("{0}: {1}\r\n", nameof(Maximum), Maximum.ToString(format));
            sb.AppendFormat("{0}: {1}\r\n", nameof(Range), Range.ToString(format));
            sb.AppendFormat("{0}: {1}\r\n", nameof(Median), Median.ToString(format));
            sb.AppendFormat("{0}: {1}\r\n", nameof(Mode), Mode.ToString(format));
            sb.AppendFormat("{0}: {1}\r\n", nameof(Sum), Sum.ToString(format));
            sb.AppendFormat("{0}: {1}\r\n", nameof(Average), Average.ToString(format));
            sb.AppendFormat("{0}: {1}\r\n", nameof(RootMeanSquare), RootMeanSquare.ToString(format));
            sb.AppendFormat("{0}: {1}\r\n", nameof(Variance), Variance.ToString(format));
            sb.AppendFormat("{0}: {1}\r\n", nameof(StandardDeviation), StandardDeviation.ToString(format));
            return(sb.ToString());
        }
Ejemplo n.º 38
0
        public void TimeAdvancesWithDataToOnlyOneSide()
        {
            var left      = new Maximum("left", 2);
            var right     = new Minimum("right", 2);
            var composite = new CompositeIndicator <IndicatorDataPoint>(left, right, (l, r) => l.Current.Value + r.Current.Value);

            Assert.AreEqual(DateTime.MinValue, composite.Current.Time);

            left.Update(Today, 1m);

            Assert.AreEqual(Today, composite.Current.Time);

            left.Update(Today.AddDays(1), -1m);

            Assert.AreEqual(Today.AddDays(1), composite.Current.Time);
        }
Ejemplo n.º 39
0
        public void ResetsProperly() {
            var left = new Maximum("left", 2);
            var right = new Minimum("right", 2);
            var composite = new CompositeIndicator<IndicatorDataPoint>(left, right, (l, r) => l + r);

            left.Update(DateTime.Today, 1m);
            right.Update(DateTime.Today,-1m);

            left.Update(DateTime.Today.AddDays(1), -1m);
            right.Update(DateTime.Today.AddDays(1), 1m);

            Assert.AreEqual(left.PeriodsSinceMaximum, 1);
            Assert.AreEqual(right.PeriodsSinceMinimum, 1);

            composite.Reset();
            TestHelper.AssertIndicatorIsInDefaultState(composite);
            TestHelper.AssertIndicatorIsInDefaultState(left);
            TestHelper.AssertIndicatorIsInDefaultState(right);
            Assert.AreEqual(left.PeriodsSinceMaximum, 0);
            Assert.AreEqual(right.PeriodsSinceMinimum, 0);
        }
Ejemplo n.º 40
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>
        /// <seealso cref="QCAlgorithm.SetStartDate(System.DateTime)"/>
        /// <seealso cref="QCAlgorithm.SetEndDate(System.DateTime)"/>
        /// <seealso cref="QCAlgorithm.SetCash(decimal)"/>
        public override void Initialize()
        {
            #region logging
            var algoname = this.GetType().Name;
            mylog.Debug(algoname);
            mylog.Debug(ondataheader);
            dailylog.Debug(algoname);
            dailylog.Debug(dailyheader);
            _transactions = new List<OrderTransaction>();

            var days = _endDate.Subtract(_startDate).TotalDays;
            MaxDailyProfit = new Maximum("MaxDailyProfit", (int)days);
            MinDailyProfit = new Minimum("MinDailyProfit", (int)days);
            #endregion

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

            //Add as many securities as you like. All the data will be passed into the event handler:
            //AddSecurity(SecurityType.Equity, symbol, Resolution.Minute);

            // Initialize the Symbol indexed dictionaries
            foreach (string s in Symbols)
            {
                AddSecurity(SecurityType.Equity, s, Resolution.Minute);
                Strategy.Add(symbol, new MultiITStrategy(s, ITrendPeriod, this));
                Tickets.Add(s, new List<OrderTicket>());
                // Equal portfolio shares for every stock.
                ShareSize.Add(s, (maxLeverage * (1 - leverageBuffer)) / Symbols.Count());
                LastOrderSent.Add(s, OrderSignal.doNothing);

                #region Logging stuff - Initializing Stock Logging

                //stockLogging.Add(new StringBuilder());
                //stockLogging[i].AppendLine("Counter, Time, Close, ITrend, Trigger," +
                //    "Momentum, EntryPrice, Signal," +
                //    "TriggerCrossOverITrend, TriggerCrossUnderITrend, ExitFromLong, ExitFromShort," +
                //    "StateFromStrategy, StateFromPorfolio, Portfolio Value");
                //i++;

                #endregion Logging stuff - Initializing Stock Logging
            }

            // Indicators
            Price = new RollingWindow<IndicatorDataPoint>(14);      // The price history

            // ITrend
            trend = new InstantaneousTrend("Main", 7, .25m);
            trendHistory = new RollingWindow<IndicatorDataPoint>(14);

            // The ITrendStrategy
            iTrendStrategy = new InstantTrendStrategy(symbol, 14, this);
            iTrendStrategy.ShouldSellOutAtEod = shouldSellOutAtEod;

            #region lists
            // Initialize the lists for the strategies
            trendList = new Dictionary<int, InstantaneousTrend>();
            trendHistoryList = new Dictionary<int, RollingWindow<IndicatorDataPoint>>();
            strategyList = new Dictionary<int, MultiITStrategy>();
            entryPriceList = new Dictionary<int, decimal>();

            int listIndex = 0;
            for (decimal d = .25m; d < .26m; d += .01m)
            {
                trendList.Add(listIndex, new InstantaneousTrend("ITrend_" + d, 7, d));  // eg ITrend.25, period 7, alpha .25
                trendHistoryList.Add(listIndex, new RollingWindow<IndicatorDataPoint>(4));
                strategyList.Add(listIndex, new MultiITStrategy(symbol, 7, this));
                entryPriceList.Add(listIndex, 0);
                listIndex++;
            }

            #endregion
            #region Proforma

            _brokerSimulator = new BrokerSimulator(this);

            #endregion
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Creates a new IchimokuKinkoHyo indicator from the specific periods
        /// </summary>
        /// <param name="name">The name of this indicator</param>
        /// <param name="tenkanPeriod">The Tenkan-sen period</param>
        /// <param name="kijunPeriod">The Kijun-sen period</param>
        /// <param name="senkouAPeriod">The Senkou A Span period</param>
        /// <param name="senkouBPeriod">The Senkou B Span period</param>
        /// <param name="senkouADelayPeriod">The Senkou A Span delay</param>
        /// <param name="senkouBDelayPeriod">The Senkou B Span delay</param>
        public IchimokuKinkoHyo(string name, int tenkanPeriod = 9, int kijunPeriod = 26, int senkouAPeriod = 26, int senkouBPeriod = 52, int senkouADelayPeriod = 26, int senkouBDelayPeriod = 26)
            : base(name)
        {
            TenkanMaximum = new Maximum(name + "_TenkanMax", tenkanPeriod);
            TenkanMinimum = new Minimum(name + "_TenkanMin", tenkanPeriod);
            KijunMaximum = new Maximum(name + "_KijunMax", kijunPeriod);
            KijunMinimum = new Minimum(name + "_KijunMin", kijunPeriod);
            SenkouBMaximum = new Maximum(name + "_SenkouBMaximum", senkouBPeriod);
            SenkouBMinimum = new Minimum(name + "_SenkouBMinimum", senkouBPeriod);
            DelayedTenkanSenkouA = new Delay(name + "DelayedTenkan", senkouADelayPeriod);
            DelayedKijunSenkouA = new Delay(name + "DelayedKijun", senkouADelayPeriod);
            DelayedMaximumSenkouB = new Delay(name + "DelayedMax", senkouBDelayPeriod);
            DelayedMinimumSenkouB = new Delay(name + "DelayedMin", senkouBDelayPeriod);


            SenkouA = new FunctionalIndicator<TradeBar>(
                name + "_SenkouA",
                input => computeSenkouA(senkouAPeriod, input),
                senkouA => DelayedTenkanSenkouA.IsReady && DelayedKijunSenkouA.IsReady,
                () =>
                {
                    Tenkan.Reset();
                    Kijun.Reset();
                });

            SenkouB = new FunctionalIndicator<TradeBar>(
                name + "_SenkouB",
                input => computeSenkouB(senkouBPeriod, input),
                senkouA => DelayedMaximumSenkouB.IsReady && DelayedMinimumSenkouB.IsReady,
                () =>
                {
                    Tenkan.Reset();
                    Kijun.Reset();
                });


            Tenkan = new FunctionalIndicator<TradeBar>(
                name + "_Tenkan",
                input => ComputeTenkan(tenkanPeriod, input),
                tenkan => TenkanMaximum.IsReady && TenkanMinimum.IsReady,
                () =>
                {
                    TenkanMaximum.Reset();
                    TenkanMinimum.Reset();
                });

            Kijun = new FunctionalIndicator<TradeBar>(
                name + "_Kijun",
                input => ComputeKijun(kijunPeriod, input),
                kijun => KijunMaximum.IsReady && KijunMinimum.IsReady,
                () =>
                {
                    KijunMaximum.Reset();
                    KijunMinimum.Reset();
                });
        }
Ejemplo n.º 42
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DonchianChannel"/> class.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="upperPeriod">The period for the upper channel.</param>
 /// <param name="lowerPeriod">The period for the lower channel</param>
 public DonchianChannel(string name, int upperPeriod, int lowerPeriod)
     : base(name)
 {
     UpperBand = new Maximum(name + "_UpperBand", upperPeriod);
     LowerBand = new Minimum(name + "_LowerBand", lowerPeriod);
 }
Ejemplo n.º 43
0
 /// <summary>
 /// Creates a new Williams %R.
 /// </summary>
 /// <param name="name">The name of this indicator</param>
 /// <param name="period">The lookback period to determine the highest high for the AroonDown</param>
 public WilliamsPercentR(string name, int period)
     : base(name)
 {
     Maximum = new Maximum(name + "_Max", period);
     Minimum = new Minimum(name + "_Min", period);
 }
Ejemplo n.º 44
0
        /// <summary>
        /// Initialize the data and resolution you require for your strategy
        /// </summary>
        public override void Initialize()
        {
            //Initialize
            SetStartDate(2013, 1, 1);
            SetEndDate(2014, 12, 31);
            SetCash(25000);

            //Add as many securities as you like. All the data will be passed into the event handler:
            AddSecurity(SecurityType.Equity, _symbol, Resolution.Minute);

            //Add the Custom Data:
            AddData<Bitcoin>("BTC");

            //Set up default Indicators, these indicators are defined on the Value property of incoming data (except ATR and AROON which use the full TradeBar object)
            _indicators = new Indicators
            {
                BB = BB(_symbol, 20, 1, MovingAverageType.Simple, Resolution.Daily),
                RSI = RSI(_symbol, 14, MovingAverageType.Simple, Resolution.Daily),
                ATR = ATR(_symbol, 14, MovingAverageType.Simple, Resolution.Daily),
                EMA = EMA(_symbol, 14, Resolution.Daily),
                SMA = SMA(_symbol, 14, Resolution.Daily),
                MACD = MACD(_symbol, 12, 26, 9, MovingAverageType.Simple, Resolution.Daily),
                AROON = AROON(_symbol, 20, Resolution.Daily),
                MOM = MOM(_symbol, 20, Resolution.Daily),
                MOMP = MOMP(_symbol, 20, Resolution.Daily),
                STD = STD(_symbol, 20, Resolution.Daily),
                MIN = MIN(_symbol, 14, Resolution.Daily), // by default if the symbol is a tradebar type then it will be the min of the low property
                MAX = MAX(_symbol, 14, Resolution.Daily)  // by default if the symbol is a tradebar type then it will be the max of the high property
            };

            // Here we're going to define indicators using 'selector' functions. These 'selector' functions will define what data gets sent into the indicator
            //  These functions have a signature like the following: decimal Selector(BaseData baseData), and can be defined like: baseData => baseData.Value
            //  We'll define these 'selector' functions to select the Low value
            //
            //  For more information on 'anonymous functions' see: http://en.wikipedia.org/wiki/Anonymous_function
            //                                                     https://msdn.microsoft.com/en-us/library/bb397687.aspx
            //
            _selectorIndicators = new Indicators
            {
                BB = BB(_symbol, 20, 1, MovingAverageType.Simple, Resolution.Daily, Field.Low),
                RSI = RSI(_symbol, 14, MovingAverageType.Simple, Resolution.Daily, Field.Low),
                EMA = EMA(_symbol, 14, Resolution.Daily, Field.Low),
                SMA = SMA(_symbol, 14, Resolution.Daily, Field.Low),
                MACD = MACD(_symbol, 12, 26, 9, MovingAverageType.Simple, Resolution.Daily, Field.Low),
                MOM = MOM(_symbol, 20, Resolution.Daily, Field.Low),
                MOMP = MOMP(_symbol, 20, Resolution.Daily, Field.Low),
                STD = STD(_symbol, 20, Resolution.Daily, Field.Low),
                MIN = MIN(_symbol, 14, Resolution.Daily, Field.High), // this will find the 14 day min of the high property
                MAX = MAX(_symbol, 14, Resolution.Daily, Field.Low),  // this will find the 14 day max of the low property

                // ATR and AROON are special in that they accept a TradeBar instance instead of a decimal, we could easily project and/or transform the input TradeBar
                // before it gets sent to the ATR/AROON indicator, here we use a function that will multiply the input trade bar by a factor of two
                ATR = ATR(_symbol, 14, MovingAverageType.Simple, Resolution.Daily, SelectorDoubleTradeBar),
                AROON = AROON(_symbol, 20, Resolution.Daily, SelectorDoubleTradeBar)
            };

            //Custom Data Indicator:
            _rsiCustom = RSI(_customSymbol, 14, MovingAverageType.Simple, Resolution.Daily);
            _minCustom = MIN(_customSymbol, 14, Resolution.Daily);
            _maxCustom = MAX(_customSymbol, 14, Resolution.Daily);

            // in addition to defining indicators on a single security, you can all define 'composite' indicators.
            // these are indicators that require multiple inputs. the most common of which is a ratio.
            // suppose we seek the ratio of BTC to SPY, we could write the following:
            var spyClose = Identity(_symbol);
            var btcClose = Identity(_customSymbol);
            // this will create a new indicator whose value is BTC/SPY
            _ratio = btcClose.Over(spyClose);
            // we can also easily plot our indicators each time they update using th PlotIndicator function
            PlotIndicator("Ratio", _ratio);
        }
Ejemplo n.º 45
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>
        /// <seealso cref="QCAlgorithm.SetStartDate(System.DateTime)"/>
        /// <seealso cref="QCAlgorithm.SetEndDate(System.DateTime)"/>
        /// <seealso cref="QCAlgorithm.SetCash(decimal)"/>
        public override void Initialize()
        {
            //Initialize dates
            SetStartDate(2015, 6, 15);
            SetEndDate(2015, 6, 15);
            SetCash(25000);

            //Add as many securities as you like. All the data will be passed into the event handler:
            AddSecurity(SecurityType.Equity, symbol, Resolution.Minute);
            #region "Init indicators"
            Price = new RollingWindow<IndicatorDataPoint>(samplesize);
            ema = new RollingWindow<IndicatorDataPoint>(samplesize);
            zema = new RollingWindow<IndicatorDataPoint>(samplesize);
            OptimalValue1 = new RollingWindow<IndicatorDataPoint>(samplesize);
            OmtimalValue2 = new RollingWindow<IndicatorDataPoint>(samplesize);
            OptimalTrackingFilter = new RollingWindow<IndicatorDataPoint>(samplesize);
            lambda = new RollingWindow<IndicatorDataPoint>(samplesize);
            alpha = new RollingWindow<IndicatorDataPoint>(samplesize);
            priceOptimalDiff = new RollingWindow<IndicatorDataPoint>(samplesize);
            priceOptimalSign = new RollingWindow<IndicatorDataPoint>(samplesize);
            priceOptimalCross = new RollingWindow<IndicatorDataPoint>(samplesize);
            fudge = new RollingWindow<IndicatorDataPoint>(samplesize);
            instantTrend = new RollingWindow<IndicatorDataPoint>(samplesize);
            instantTrendTrigger = new RollingWindow<IndicatorDataPoint>(samplesize);
            cyberCycle = new RollingWindow<IndicatorDataPoint>(samplesize);
            centerGravity = new RollingWindow<IndicatorDataPoint>(samplesize);
            cyberCycleSmooth = new RollingWindow<IndicatorDataPoint>(samplesize);
            rvi = new RelativeVigorIndex(8);
            rviHistory = new RollingWindow<IndicatorDataPoint>(samplesize);

            stochCenterGravityValue1 = new RollingWindow<IndicatorDataPoint>(8);
            stochCenterGravityValue2 = new RollingWindow<IndicatorDataPoint>(8);

            stochCyberCycleValue1 = new RollingWindow<IndicatorDataPoint>(8);
            stochCyberCycleValue2 = new RollingWindow<IndicatorDataPoint>(8);
            stochCyberCycleInverseFisher = new RollingWindow<IndicatorDataPoint>(8);
            stochCyberCycleFisher = new RollingWindow<IndicatorDataPoint>(8);

            stochRviHistoryValue1 = new RollingWindow<IndicatorDataPoint>(8);
            stochRviHistoryValue2 = new RollingWindow<IndicatorDataPoint>(8);

            ROC = new RateOfChange(4);
            maxCyberCycle = new Maximum(8);
            minCyberCycle = new Minimum(8);
            #endregion
            //mylog.Debug(transheader);
            mylog.Debug(ondataheader);
            string msg = "Security,Date,Day Profit,Day Fees, Day Net, Total Profit, Total Fees";
            mylog.Debug(msg);
            mylog.Debug(tradeheader);
        }
Ejemplo n.º 46
0
    public static void Main(string[] args)
    {
        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyMediaLite.Util.Handlers.UnhandledExceptionHandler);
        Console.CancelKeyPress += new ConsoleCancelEventHandler(AbortHandler);

        // recommender arguments
        string method              = null;
        string recommender_options = string.Empty;

        // help/version
        bool show_help    = false;
        bool show_version = false;

        // variables for iteration search
        int max_iter   = 500;
        double cutoff  = 0;
        double epsilon = 0;
        string measure = "AUC";

        compute_fit         = false;

        // other parameters
        test_ratio         = 0;
        num_test_users     = -1;
        repeat_eval        = false;

        var p = new OptionSet() {
            // string-valued options
            { "training-file=",       v => training_file          = v },
            { "test-file=",           v => test_file              = v },
            { "recommender=",         v => method                 = v },
            { "group-recommender=",   v => group_method           = v },
            { "recommender-options=", v => recommender_options   += " " + v },
            { "data-dir=",            v => data_dir               = v },
            { "user-attributes=",     v => user_attributes_file   = v },
            { "item-attributes=",     v => item_attributes_file   = v },
            { "user-relations=",      v => user_relations_file    = v },
            { "item-relations=",      v => item_relations_file    = v },
            { "save-model=",          v => save_model_file        = v },
            { "load-model=",          v => load_model_file        = v },
            { "save-user-mapping=",   v => save_user_mapping_file = v },
            { "save-item-mapping=",   v => save_item_mapping_file = v },
            { "load-user-mapping=",   v => load_user_mapping_file = v },
            { "load-item-mapping=",   v => load_item_mapping_file = v },
            { "prediction-file=",     v => prediction_file        = v },
            { "test-users=",          v => test_users_file        = v },
            { "candidate-items=",     v => candidate_items_file   = v },
            { "user-groups=",         v => user_groups_file       = v },
            { "measure=",             v => measure                = v },
            // integer-valued options
            { "find-iter=",            (int v) => find_iter            = v },
            { "max-iter=",             (int v) => max_iter             = v },
            { "random-seed=",          (int v) => random_seed          = v },
            { "predict-items-number=", (int v) => predict_items_number = v },
            { "num-test-users=",       (int v) => num_test_users       = v },
            { "cross-validation=",     (uint v) => cross_validation    = v },
            // floating point options
            { "epsilon=",             (double v)     => epsilon      = v },
            { "cutoff=",              (double v)     => cutoff       = v },
            { "test-ratio=",          (double v) => test_ratio       = v },
            { "rating-threshold=",    (float v)  => rating_threshold = v },
            // enum options
            { "file-format=",         (ItemDataFileFormat v) => file_format = v },
            // boolean options
            { "user-prediction",      v => user_prediction   = v != null },
            { "compute-fit",          v => compute_fit       = v != null },
            { "online-evaluation",    v => online_eval       = v != null },
            { "repeat-evaluation",    v => repeat_eval       = v != null },
            { "no-id-mapping",        v => no_id_mapping     = v != null },
            { "overlap-items",        v => overlap_items     = v != null },
            { "all-items",            v => all_items         = v != null },
            { "in-training-items",    v => in_training_items = v != null },
            { "in-test-items",        v => in_test_items     = v != null },
            { "help",                 v => show_help         = v != null },
            { "version",              v => show_version      = v != null },
        };
        IList<string> extra_args = p.Parse(args);

        bool no_eval = true;
        if (test_ratio > 0 || test_file != null)
            no_eval = false;

        if (show_version)
            ShowVersion();
        if (show_help)
            Usage(0);

        if (random_seed != -1)
            MyMediaLite.Util.Random.Seed = random_seed;

        // set up recommender
         		if (load_model_file != null)
            recommender = Model.Load(load_model_file);
        else if (method != null)
            recommender = Recommender.CreateItemRecommender(method);
        else
            recommender = Recommender.CreateItemRecommender("MostPopular");
        // in case something went wrong ...
        if (recommender == null && method != null)
            Usage(string.Format("Unknown recommendation method: '{0}'", method));
        if (recommender == null && load_model_file != null)
            Abort(string.Format("Could not load model from file {0}.", load_model_file));

        CheckParameters(extra_args);

        recommender.Configure(recommender_options, (string m) => { Console.Error.WriteLine(m); Environment.Exit(-1); });

        if (no_id_mapping)
        {
            user_mapping = new IdentityMapping();
            item_mapping = new IdentityMapping();
        }
        if (load_user_mapping_file != null)
            user_mapping = EntityMappingExtensions.LoadMapping(load_user_mapping_file);
        if (load_item_mapping_file != null)
            item_mapping = EntityMappingExtensions.LoadMapping(load_item_mapping_file);

        // load all the data
        LoadData();
        Console.Write(training_data.Statistics(test_data, user_attributes, item_attributes));

        // if requested, save ID mappings
        if (save_user_mapping_file != null)
            user_mapping.SaveMapping(save_user_mapping_file);
        if (save_item_mapping_file != null)
            item_mapping.SaveMapping(save_item_mapping_file);

        TimeSpan time_span;

        if (find_iter != 0)
        {
            if ( !(recommender is IIterativeModel) )
                Abort("Only iterative recommenders (interface IIterativeModel) support --find-iter=N.");

            var iterative_recommender = (IIterativeModel) recommender;
            Console.WriteLine(recommender);
            var eval_stats = new List<double>();

            if (cross_validation > 1)
            {
                recommender.DoIterativeCrossValidation(cross_validation, test_users, candidate_items, eval_item_mode, repeat_eval, max_iter, find_iter);
            }
            else
            {
                if (load_model_file == null)
                    recommender.Train();

                if (compute_fit)
                    Console.WriteLine("fit: {0} iteration {1} ", ComputeFit(), iterative_recommender.NumIter);

                var results = Evaluate();
                Console.WriteLine("{0} iteration {1}", results, iterative_recommender.NumIter);

                for (int it = (int) iterative_recommender.NumIter + 1; it <= max_iter; it++)
                {
                    TimeSpan t = Wrap.MeasureTime(delegate() {
                        iterative_recommender.Iterate();
                    });
                    training_time_stats.Add(t.TotalSeconds);

                    if (it % find_iter == 0)
                    {
                        if (compute_fit)
                        {
                            t = Wrap.MeasureTime(delegate() {
                                Console.WriteLine("fit: {0} iteration {1} ", ComputeFit(), it);
                            });
                            fit_time_stats.Add(t.TotalSeconds);
                        }

                        t = Wrap.MeasureTime(delegate() { results = Evaluate(); });
                        eval_time_stats.Add(t.TotalSeconds);
                        eval_stats.Add(results[measure]);
                        Console.WriteLine("{0} iteration {1}", results, it);

                        Model.Save(recommender, save_model_file, it);
                        Predict(prediction_file, test_users_file, it);

                        if (epsilon > 0.0 && eval_stats.Max() - results[measure] > epsilon)
                        {
                            Console.Error.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0} >> {1}", results["RMSE"], eval_stats.Min()));
                            Console.Error.WriteLine("Reached convergence on training/validation data after {0} iterations.", it);
                            break;
                        }
                        if (results[measure] < cutoff)
                        {
                                Console.Error.WriteLine("Reached cutoff after {0} iterations.", it);
                                Console.Error.WriteLine("DONE");
                                break;
                        }
                    }
                } // for
            }
        }
        else
        {
            Console.WriteLine(recommender + " ");

            if (load_model_file == null)
            {
                if (cross_validation > 1)
                {
                    var results = recommender.DoCrossValidation(cross_validation, test_users, candidate_items, eval_item_mode, compute_fit, true);
                    Console.Write(results);
                    no_eval = true;
                }
                else
                {
                    time_span = Wrap.MeasureTime( delegate() { recommender.Train(); } );
                    Console.Write("training_time " + time_span + " ");
                }
            }

            if (prediction_file != null)
            {
                Predict(prediction_file, test_users_file);
            }
            else if (!no_eval)
            {
                if (compute_fit)
                    Console.WriteLine("fit: {0}", ComputeFit());

                if (online_eval)
                    time_span = Wrap.MeasureTime( delegate() {
                        var results = recommender.EvaluateOnline(test_data, training_data, test_users, candidate_items, eval_item_mode);
                        Console.Write(results);
                    });
                else if (group_method != null)
                {
                    GroupRecommender group_recommender = null;

                    Console.Write("group recommendation strategy: {0} ", group_method);
                    // TODO GroupUtils.CreateGroupRecommender(group_method, recommender);
                    if (group_method == "Average")
                        group_recommender = new Average(recommender);
                    else if (group_method == "Minimum")
                        group_recommender = new Minimum(recommender);
                    else if (group_method == "Maximum")
                        group_recommender = new Maximum(recommender);
                    else
                        Usage("Unknown group recommendation strategy in --group-recommender=METHOD");

                    time_span = Wrap.MeasureTime( delegate() {
                        var result = group_recommender.Evaluate(test_data, training_data, group_to_user, candidate_items);
                        Console.Write(result);
                    });
                }
                else
                    time_span = Wrap.MeasureTime( delegate() { Console.Write(Evaluate()); });
                Console.Write(" testing_time " + time_span);
            }
            Console.WriteLine();
        }
        Model.Save(recommender, save_model_file);
        DisplayStats();
    }
Ejemplo n.º 47
0
 /// <summary>
 /// AroonUp = 100 * (period - {periods since max})/period
 /// </summary>
 /// <param name="upPeriod">The AroonUp period</param>
 /// <param name="max">A Maximum indicator used to compute periods since max</param>
 /// <param name="input">The next input data</param>
 /// <returns>The AroonUp value</returns>
 private static decimal ComputeAroonUp(int upPeriod, Maximum max, IndicatorDataPoint input)
 {
     max.Update(input);
     return 100m * (upPeriod - max.PeriodsSinceMaximum) / upPeriod;
 }