Ejemplo n.º 1
0
        public void TestEMA()
        {
            long ticks = 1000;
            var data = new double[] { 20, 40, 22, 35, 33, 78, 21, 45, 33, 5, 67, 22, 98, 22, 34, 54 };
            var input = new TimeSeries();
            var ema = new EMA(input, 10);
            foreach (var d in data)
                input.Add(new DateTime().AddTicks(ticks++), d);
            for (var i = 0; i < ema.Count; i++)
                output.WriteLine(ema[i].ToString());


            Assert.Equal(ema[0], 20, precision);
            Assert.Equal(ema[1], 23.6363636363636, precision);
            Assert.Equal(ema[2], 23.3388429752066, precision);
            Assert.Equal(ema[3], 25.4590533433509, precision);
            Assert.Equal(ema[4], 26.8301345536507, precision);
            Assert.Equal(ema[5], 36.1337464529869, precision);
            Assert.Equal(ema[6], 33.3821561888075, precision);
            Assert.Equal(ema[7], 35.4944914272061, precision);
            Assert.Equal(ema[8], 35.0409475313505, precision);
            Assert.Equal(ema[9], 29.5789570711049, precision);
            Assert.Equal(ema[10], 36.3827830581768, precision);
            Assert.Equal(ema[11], 33.7677315930537, precision);
            Assert.Equal(ema[12], 45.4463258488621, precision);
            Assert.Equal(ema[13], 41.1833575127054, precision);
            Assert.Equal(ema[14], 39.8772925103953, precision);
            Assert.Equal(ema[15], 42.4450575085053, precision);
        }
Ejemplo n.º 2
0
 public TimeDecayLinear(decimal linearDecay, TimeSpan mobilePeriodLength)
     : base(mobilePeriodLength)
 {
     _startCoeff = 2m / (1m + linearDecay);
     _endCoeff = 2m - _startCoeff;
     _timeDecayWeight = new TimeSeries();
 }
Ejemplo n.º 3
0
 public static double GetRegularTimeStepLengthDays(TimeSeries ts)
 {
     var t = ts.timeStep as EvenTimeStep;
     if (t == null)
         return -1;
     return t.span.TotalDays;
 }
Ejemplo n.º 4
0
        public static TimeSeriesComplexType FromTimeSeries(TimeSeries ts,string forcedTimeStamp)
        {
            TimeSeriesComplexType result = new TimeSeriesComplexType( );

            string locationName = LocationName(ts.name);
            result.header = new HeaderComplexType
                {
                    type = timeSeriesType.mean,
                    locationId = locationName,
                    //stationName = locationName,
                    startDate = new DateTimeComplexType {DateTime = MergeDT(ts.Start,forcedTimeStamp)},
                    endDate = new DateTimeComplexType {DateTime = MergeDT(ts.End,forcedTimeStamp)},
                    missVal = ts.NullValue,
                    units = PIUnits(ts),
                    timeStep = PITimeStep(ts.timeStep),
                    parameterId = ParameterName(ts.name)
                };

            IList<EventComplexType> events = new List<EventComplexType>();
            for (int i = 0; i < ts.count(); i++)
            {
                var fewsDT = new DateTimeComplexType {DateTime = MergeDT(ts.timeForItem(i),forcedTimeStamp)};
                events.Add( new EventComplexType
                    {
                        date = fewsDT.date,
                        time = fewsDT.time,
                        flag = 2,
                        flagSpecified = true,
                        value = ts[i]
                    });
            }

            result.@event = events.ToArray();
            return result;
        }
Ejemplo n.º 5
0
Archivo: code.cs Proyecto: heber/FreeOQ
	public override void OnStrategyStart()
	{
		series = new BarSeries();

		if (VolatilityExitEnabled || VolatilityBarrierEnabled)
		{
			rangeSeries = new TimeSeries();
			
			rangeSMA = new SMA(rangeSeries, VolatilitySMALength);
		}
		
		if (TickBarrierEnabled)
			barrier = TickSize * BarrierSize;
		
		lowestLowSeries   = new TimeSeries();
		highestHighSeries = new TimeSeries();		
		channelLowSeries  = new TimeSeries();
		channelHighSeries = new TimeSeries();
		
		lowestLowSeries  .Color = Color.Blue;
		highestHighSeries.Color = Color.Blue;
		channelLowSeries .Color = Color.Brown;
		channelHighSeries.Color = Color.Brown;
		
		Draw(lowestLowSeries  , 0);
		Draw(highestHighSeries, 0);
		Draw(channelLowSeries , 0);
		Draw(channelHighSeries, 0);
	}
        public TimeSeries<string> historySeries(DateTime sDate, DateTime eDate )
        {
            TimeSeries<string> hist = new TimeSeries<string>();

            INDEX_DATA_Table_DAOManager dao_m = new INDEX_DATA_Table_DAOManager();

            dao_m.INDEX_CODE_ = this.Code_;
            
            dao_m.selectInterval(DataBaseConnectManager.ConnectionFactory("myDB"),sDate,eDate);

            foreach (var item in dao_m.DAOList_)
            {
                string date = item.INDEX_DATE_;

                int year =  Convert.ToInt32(date.Substring(0, 4));
                int month = Convert.ToInt32(date.Substring(4, 2));
                int day = Convert.ToInt32(date.Substring(6, 2));

                string value = item.INDEX_VALUE_;

                hist.Add(new Date(new DateTime(year,month, day)), value);

            }

            return hist;
        }
Ejemplo n.º 7
0
 public Model()
 {
     ts = null;
     seasonal = null;
     values = null;
     errors = null;
 }
Ejemplo n.º 8
0
        public ListItem(TimeSeries ts, int resultNo, double error, bool showIndex = false)
        {
            ResultNo = resultNo;
            TimeSeriesData = ts;
            Error = error;
            ShowIndex = showIndex;

            Render(ts);
        }
Ejemplo n.º 9
0
 public EWV(ISeries input, double length, double initValue = 0) : base(input)
 {
     Length = length;
     InitValue = initValue;
     this.ewm_0 = new EWM(input, length);
     this.ewm_0.AutoUpdate = false;
     this.timeSeries_0 = new TimeSeries();
     this.ewm_1 = new EWM(this.timeSeries_0, length);
 }
Ejemplo n.º 10
0
 protected override void Init()
 {
     this.name = $"PDI ({this.length})";
     this.description = "Plus Directional Indicator";
     Clear();
     this.calculate = true;
     this.pdmTS = new TimeSeries();
     this.trTS = new TimeSeries();
 }
Ejemplo n.º 11
0
 protected override void Init()
 {
     this.name = $"DX ({this.length})";
     this.description = "Directional Movement Index";
     Clear();
     this.calculate = true;
     this.pdmTS = new TimeSeries();
     this.mdmTS = new TimeSeries();
 }
Ejemplo n.º 12
0
		protected override void Init()
		{
			this.name = "MDI (" + this.length + ")";
			this.description = "Minus Directional Indicator";
			base.Clear();
			this.calculate = true;
			this.mdmTS = new TimeSeries();
			this.trTS = new TimeSeries();
		}
Ejemplo n.º 13
0
        public void addFixings(List<Date> d, List<double> v, bool forceOverwrite) {
            if ((d.Count != v.Count) || d.Count == 0)
                throw new ArgumentException("Wrong collection dimensions when creating index fixings");

            TimeSeries<double> t = new TimeSeries<double>();
            for(int i=0; i<d.Count; i++)
                t.Add(d[i], v[i]);
            addFixings(t, forceOverwrite);
        }
Ejemplo n.º 14
0
        public TimeSeriesComparison(TimeSeries ts1, TimeSeries ts2, double start, double end, double error)
        {
            Ts1 = ts1;
            Ts2 = ts2;
            Error = error;

            IsPruned = true;
            Start = start;
            End = end;
        }
Ejemplo n.º 15
0
 public static double Value(ISeries input, int index, int length1, int length2)
 {
     if (index >= length1 - 1 && index >= length2 - 1)
     {
         var ts = new TimeSeries();
         for (var i = index - Math.Max(length1, length2) + 1; i <= index; i++)
             ts.Add(input.GetDateTime(i), input[i, BarData.Volume]);
         return SMA.Value(ts, length1 - 1, length1) - SMA.Value(ts, length2 - 1, length2);
     }
     return double.NaN;
 }
Ejemplo n.º 16
0
 protected override void Init()
 {
     this.name = this.input is BarSeries
         ? $"RSI ({this.length}, {this.barData})"
         : $"RSI ({this.length})";
     this.description = "Relative Strength Index";
     Clear();
     this.calculate = true;
     this.upTS = new TimeSeries();
     this.downTS = new TimeSeries();
 }
Ejemplo n.º 17
0
 public static double Value(ISeries input, int index, int length1, int length2)
 {
     if (index >= length2 - 1)
     {
         var ts = new TimeSeries();
         for (var i = 0; i <= index; i++)
             ts.Add(input.GetDateTime(i), input[i, BarData.High] - input[i, BarData.Low]);
         var ema = new EMA(ts, length1);
         return (ema[index] - ema[index - length2 + 1])/ema[index - length2 + 1]*100;
     }
     return double.NaN;
 }
Ejemplo n.º 18
0
        protected override void Init()
        {
            this.name = $"VCH ({this.length1}, {this.length2})";
            this.description = "Chaikin Volatility";
            Clear();
            this.calculate = true;

            this.hlTS = new TimeSeries();
            for (var i = 0; i < this.input.Count; i++)
                this.hlTS.Add(this.input.GetDateTime(i), this.input[i, BarData.High] - this.input[i, BarData.Low]);
            this.ema = new EMA(this.hlTS, this.length1);
        }
Ejemplo n.º 19
0
 public static TimeSeriesLink BuildLink(TimeSeries ts, ProjectViewRow row, AttributeRecordingState key, int runNumber)
 {
     return new TimeSeriesLink
     {
         TimeSeriesName = ts.name,
         RunNumber = runNumber,
         TimeSeriesUrl = BuildTimeSeriesUrl(row,key, runNumber),
         NetworkElement = row.NetworkElementName,
         RecordingElement = row.ElementName,
         RecordingVariable = SelectRecordingVariable(key, row)
     };
 }
Ejemplo n.º 20
0
        public EstimationResult Estimate(IEnumerable<IDateValue> dateValues)
        {
            var series = new TimeSeries();
            dateValues.ForEach(x => series.Add(x.Date, x.Value, true));

            armaModel.SetInput(0, series, null);
            armaModel.FitByMLE(200, 100, 0, null);
            armaModel.ComputeResidualsAndOutputs();

            var result = armaModel.GetOutput(3) as TimeSeries;
            return EstimationResult.Create(result[0], this);
        }
Ejemplo n.º 21
0
        public ListItem(TimeSeries ts, bool isPruned, double highlightStart, double highlightEnd,
            int resultNo, double error, bool showIndex = false)
        {
            ResultNo = resultNo;
            TimeSeriesData = ts;
            Error = error;
            IsPruned = isPruned;
            HighlightStart = highlightStart;
            HighlightEnd = highlightEnd;
            ShowIndex = showIndex;

            Render(ts);
        }
Ejemplo n.º 22
0
 public static bool TestTimeSeries(TimeSeries ts, double[] expValues, string expTimeStep, DateTime expectedStart)
 {
     var tsv = ts.ToArray();
     if (tsv.Length != expValues.Length) return false;
     for (int i = 0; i < tsv.Length; i++)
         if (isDifferent(tsv[i], expValues[i])) return false;
     if (ts.timeStep.ToString() != expTimeStep)
         return false;
     // TODO: even for a constructed time series with a start date with kind Utc specified, the time series property
     // ends up with a start date time of kind Unspecified. Very curious; may be a TIME 'issue
     // if (ts.Start != expectedStart) return false;
     return true;
 }
Ejemplo n.º 23
0
        public TimeSeries GetResampled(TimeSeries timeSeriesData, int numSamples)
        {
            var kv = new TimeSeriesSamplingRatePair(timeSeriesData, numSamples);
            if (StockTimeSeries.ContainsKey(kv))
            {
                return StockTimeSeries[kv];
            }

            var ts = new TimeSeries(timeSeriesData.Values);
            TimeSeries resampled = ts.GetResampled(numSamples);
            StockTimeSeries.Add(kv, resampled);
            return resampled;
        }
Ejemplo n.º 24
0
 public static double Value(ISeries input, int index, int length, int order)
 {
     if (index >= length - 1)
     {
         var ts = new TimeSeries();
         for (int i = 0; i <= index; i++)
             ts.Add(input.GetDateTime(i), input[i, BarData.High] - input[i, BarData.Low]);
         var ema = new EMA(ts, order);
         var ema_ema = new EMA(ema, order);
         return Enumerable.Range(index - length + 1, length).Reverse().Sum(i => ema[i]/ema_ema[i]);
     }
     return double.NaN;
 }
Ejemplo n.º 25
0
		public static double Value(ISeries input, int index, int length1, int length2)
		{
			if (index >= length2 - 1)
			{
				TimeSeries timeSeries = new TimeSeries();
				for (int i = 0; i <= index; i++)
				{
					timeSeries.Add(input.GetDateTime(i), input[i, BarData.High] - input[i, BarData.Low]);
				}
				EMA eMA = new EMA(timeSeries, length1, BarData.Close);
				return (eMA[index] - eMA[index - length2 + 1]) / eMA[index - length2 + 1] * 100.0;
			}
			return double.NaN;
		}
Ejemplo n.º 26
0
 protected override void Init()
 {
     this.name = $"MASS ({this.length}, {this.order})";
     this.description = "Mass Index";
     Clear();
     this.calculate = true;
     this.hlTS = new TimeSeries();
     for (var i = 0; i < this.input.Count; i++)
         this.hlTS.Add(this.input.GetDateTime(i), this.input[i, BarData.High] - this.input[i, BarData.Low]);
     Detach();
     this.ema = new EMA(this.hlTS, this.order);
     this.ema_ema = new EMA(this.ema, this.order);
     Attach();
 }
Ejemplo n.º 27
0
		public static double Value(ISeries input, int index, int length1, int length2)
		{
			if (index >= length1 - 1 && index >= length2 - 1)
			{
				TimeSeries timeSeries = new TimeSeries();
				for (int i = index - Math.Max(length1, length2) + 1; i <= index; i++)
				{
					timeSeries.Add(input.GetDateTime(i), input[i, BarData.Volume]);
				}
				double num = SMA.Value(timeSeries, length1 - 1, length1, BarData.Close);
				double num2 = SMA.Value(timeSeries, length2 - 1, length2, BarData.Close);
				return num - num2;
			}
			return double.NaN;
		}
Ejemplo n.º 28
0
        public static TimeSeries CreateWaterLevelTimeSeries()
        {
            var ts = new TimeSeries
                {
                    Components = {new Variable<double>("level", new Unit("m AD", "m AD"))},
                    Name = "water level time series"
                };
            ts.Components[0].Attributes[FunctionAttributes.StandardName] = FunctionAttributes.StandardNames.WaterLevel;
            var variable = ts.Arguments.First();
            variable.DefaultValue = new DateTime(2000, 1, 1);
            variable.InterpolationType = InterpolationType.Linear;
            variable.ExtrapolationType = ExtrapolationType.Constant;

            return ts;
        }
Ejemplo n.º 29
0
 public void TestWMA()
 {
     long ticks = 1000;
     var data = new double[] { 20, 40, 22, 35, 33, 78, 21, 45, 33, 5, 67, 22, 98, 22, 34, 54 };
     var input = new TimeSeries();
     var wma = new WMA(input, 10);
     foreach (var d in data)
         input.Add(new DateTime().AddTicks(ticks++), d);
     Assert.Equal(wma[0], 32.6, precision);
     Assert.Equal(wma[1], 38.7454545454545, precision);
     Assert.Equal(wma[2], 35.8545454545455, precision);
     Assert.Equal(wma[3], 47.1090909090909, precision);
     Assert.Equal(wma[4], 43.1636363636364, precision);
     Assert.Equal(wma[5], 41.6363636363636, precision);
     Assert.Equal(wma[6], 43.7272727272727, precision);
 }
Ejemplo n.º 30
0
        public SimpleTimeSeries(TimeSeries source):base(source)
        {
            if (source == null)
            {
                Events = new TimeSeriesEvent[0];
                return;
            }

            IList<TimeSeriesEvent> eventList = new List<TimeSeriesEvent>();
            for (int i = 0; i < source.count(); i++)
                eventList.Add(new TimeSeriesEvent
                    {
                        Date = source.timeForItem(i).ToString(CultureInfo.InvariantCulture),
                        Value = source[i]
                    });

            Events = eventList.ToArray();
        }
Ejemplo n.º 31
0
        public TimeSeries GetPriceReturnTimeSeries()
        {
            TimeSeries last_ts = this.GetTimeSeries(TimeSeriesType.Close);

            if (last_ts == null || last_ts.Count == 0)
            {
                return(null);
            }

            int count = last_ts.Count;

            DateTime lastDate = last_ts.DateTimes[count - 1];

            if (_prDB.ContainsKey(lastDate))
            {
                return(_prDB[lastDate]);
            }



            TimeSeries tr_ts = new TimeSeries(1);

            tr_ts.AddDataPoint(last_ts.DateTimes[0], last_ts[0]);

            for (int i = 1; i < count; i++)
            {
                DateTime date    = last_ts.DateTimes[i];
                DateTime date_1  = last_ts.DateTimes[i - 1];
                double   value   = last_ts[i];
                double   value_1 = last_ts[i - 1];

                //var corps = this.CorporateActions(date_1.Date);
                var corps = this.CorporateActions(date.Date);
                if (corps != null)
                {
                    foreach (CorporateAction corp in corps)
                    {
                        //Console.WriteLine(corp);

                        double amount = corp.Amount;
                        if (corp.Type != "Stock Split" && corp.Type != "Scrip" && corp.Type != "Spinoff")
                        {
                            value += amount * 0;// No Dividend Reinvestment
                        }
                        else if (corp.Type == "Spinoff" && corp.Amount != 1.0)
                        {
                            value /= 1 - amount;
                        }
                        else if (corp.Type == "Stock Split")
                        {
                            value *= amount;
                        }
                        else if (corp.Type == "Scrip" && corp.Amount != 0.0)
                        {
                            value /= amount;
                        }
                    }
                }


                double v_1 = tr_ts[i - 1];
                double v   = v_1 * (value / value_1);
                tr_ts.AddDataPoint(date, v);
            }

            double scale = last_ts[count - 1] / tr_ts[count - 1];

            tr_ts *= scale;

            _prDB.TryAdd(lastDate, tr_ts);

            return(tr_ts);
        }
Ejemplo n.º 32
0
        public TimeSeries GetTotalReturnTimeSeries()
        {
            TimeSeries last_ts = this.GetTimeSeries(TimeSeriesType.Close);

            if (last_ts == null || last_ts.Count == 0)
            {
                return(null);
            }

            int count = last_ts.Count;

            DateTime lastDate = last_ts.DateTimes[count - 1];

            if (_trDB.ContainsKey(lastDate))
            {
                return(_trDB[lastDate]);
            }



            TimeSeries tr_ts = new TimeSeries(1);

            tr_ts.AddDataPoint(last_ts.DateTimes[0], last_ts[0]);

            var all_corps = this.CorporateActions();

            for (int i = 1; i < count; i++)
            {
                DateTime date    = last_ts.DateTimes[i];
                DateTime date_1  = last_ts.DateTimes[i - 1];
                double   value   = last_ts[i];
                double   value_1 = last_ts[i - 1];


                double adjustment = 1.0;
                foreach (CorporateAction c in all_corps)
                {
                    if (c.ExDate >= date.Date)
                    {
                        if (c.Type == "Stock Split")
                        {
                            adjustment *= c.Amount;
                        }
                        else if (c.Type == "Scrip" && c.Amount != 0.0)
                        {
                            adjustment /= c.Amount;
                        }
                        else if (c.Type == "Spinoff" && c.Amount != 1.0)
                        {
                            adjustment /= 1 - c.Amount;
                        }
                    }
                }

                var corps = this.CorporateActions(date.Date);
                if (corps != null)
                {
                    foreach (CorporateAction corp in corps)
                    {
                        double amount = corp.Amount;
                        if (corp.Type != "Stock Split" && corp.Type != "Scrip" && corp.Type != "Spinoff")// && corp.Type != "Rights Issue")
                        {
                            value += amount * adjustment;
                        }
                        else if (corp.Type == "Spinoff" && corp.Amount != 1.0)
                        {
                            value /= 1 - amount;
                        }

                        else if (corp.Type == "Stock Split")
                        {
                            value *= amount;
                        }
                        else if (corp.Type == "Scrip" && corp.Amount != 0.0)
                        {
                            value /= amount;
                        }
                    }
                }


                double v_1 = tr_ts[i - 1];
                double v   = v_1 * (value / value_1);
                tr_ts.AddDataPoint(date, v);
            }

            double scale = last_ts[count - 1] / tr_ts[count - 1];

            tr_ts *= scale;

            _trDB.TryAdd(lastDate, tr_ts);

            return(tr_ts);
        }
Ejemplo n.º 33
0
        public void Draw()
        {
            UltiDraw.Begin();

            //DEBUG RENDERING
            // {
            //  float _xMin = 0.025f;
            //  float _xMax = 0.25f;
            //  float _yMin = 0.05f;
            //  float _yMax = 0.25f;
            //  for(int b=0; b<Bones.Length; b++) {
            //      float w = (float)b/(float)(Bones.Length-1);
            //      List<float[]> values = new List<float[]>();
            //      float max = 0f;
            //      float[] first = new float[TimeSeries.FutureKeyCount+1];
            //      float[] second = new float[TimeSeries.FutureKeyCount+1];
            //      float[] third = new float[TimeSeries.FutureKeyCount+1];
            //      for(int i=0; i<TimeSeries.FutureKeyCount+1; i++) {
            //          first[i] = _PhaseMagnitudes[TimeSeries.GetKey(i+TimeSeries.PivotKey).Index][b];
            //          second[i] = _PhaseStates[TimeSeries.GetKey(i+TimeSeries.PivotKey).Index][b].magnitude;
            //          third[i] = _PhaseUpdateVectors[TimeSeries.GetKey(i+TimeSeries.PivotKey).Index][b].magnitude;
            //          max = Mathf.Max(max, first[i], second[i], third[i]);
            //      }
            //      values.Add(first);
            //      values.Add(second);
            //      values.Add(third);
            //      float vertical = Utility.Normalise(w, 0f, 1f, _yMin, _yMax);
            //      float height = 0.95f*(_yMax-_yMin)/(Bones.Length-1);
            //      UltiDraw.DrawGUIFunctions(new Vector2(0.5f * (_xMin + _xMax), vertical), new Vector2(_xMax-_xMin, height), values, 0f, max, UltiDraw.DarkGrey, new Color[3]{Color.yellow, Color.magenta, Color.cyan});
            //  }
            // }
            // {
            //  float _xMin = 0.025f;
            //  float _xMax = 0.25f;
            //  float _yMin = 0.3f;
            //  float _yMax = 0.5f;
            //  for(int b=0; b<Bones.Length; b++) {
            //      float w = (float)b/(float)(Bones.Length-1);
            //      List<float[]> values = new List<float[]>();
            //      float[] first = new float[TimeSeries.FutureKeyCount+1];
            //      float[] second = new float[TimeSeries.FutureKeyCount+1];
            //      for(int i=0; i<TimeSeries.FutureKeyCount+1; i++) {
            //          first[i] = _PhaseUpdateValues[TimeSeries.GetKey(i+TimeSeries.PivotKey).Index][b];
            //          second[i] = Utility.PhaseUpdate(0f, Utility.PhaseValue(_PhaseUpdateVectors[TimeSeries.GetKey(i+TimeSeries.PivotKey).Index][b]));
            //      }
            //      values.Add(first);
            //      values.Add(second);
            //      float vertical = Utility.Normalise(w, 0f, 1f, _yMin, _yMax);
            //      float height = 0.95f*(_yMax-_yMin)/(Bones.Length-1);
            //      UltiDraw.DrawGUIFunctions(new Vector2(0.5f * (_xMin + _xMax), vertical), new Vector2(_xMax-_xMin, height), values, 0f, 0.1f, UltiDraw.DarkGrey, new Color[2]{Color.yellow, Color.magenta});
            //  }
            // }
            //

            float xMin = 0.3f;
            float xMax = 0.7f;
            float yMin = 0.75f;
            float yMax = 0.95f;

            //This is phase vector rendering
            for (int b = 0; b < Bones.Length; b++)
            {
                float   w      = (float)b / (float)(Bones.Length - 1);
                float[] values = new float[TimeSeries.KeyCount];
                Color[] colors = new Color[TimeSeries.KeyCount];
                for (int i = 0; i < TimeSeries.KeyCount; i++)
                {
                    values[i] = Phases[TimeSeries.GetKey(i).Index][b];
                    colors[i] = UltiDraw.White.Transparent(Magnitudes[TimeSeries.GetKey(i).Index][b]);
                }
                float vertical = Utility.Normalise(w, 0f, 1f, yMin, yMax);
                float height   = 0.95f * (yMax - yMin) / (Bones.Length - 1);
                UltiDraw.DrawGUIBars(new Vector2(0.5f * (xMin + xMax), vertical), new Vector2(xMax - xMin, height), values, 1f, 1f, 0.01f, UltiDraw.DarkGrey, Color.white);
                // UltiDraw.DrawGUICircularPivot(new Vector2(xMax + height/2f, vertical), height/2f, UltiDraw.DarkGrey, 360f*Phases[TimeSeries.Pivot][b], 1f, colors[TimeSeries.PivotKey]);
                UltiDraw.DrawGUICircularPivot(new Vector2(xMax + height / 2f, vertical), height / 2f, UltiDraw.DarkGrey, 360f * Phases[TimeSeries.Pivot][b], Magnitudes[TimeSeries.Pivot][b], colors[TimeSeries.PivotKey]);

                for (int i = 0; i < TimeSeries.KeyCount; i++)
                {
                    float horizontal = Utility.Normalise((float)i / (float)(TimeSeries.KeyCount - 1), 0f, 1f, xMin, xMax);
                    // UltiDraw.DrawGUICircularPivot(new Vector2(horizontal, vertical + height/4f), height/4f, UltiDraw.DarkGrey, 360f*Phases[TimeSeries.GetKey(i).Index][b], 1f, colors[i]);
                    UltiDraw.DrawGUICircularPivot(new Vector2(horizontal, vertical + height / 4f), height / 4f, UltiDraw.DarkGrey, 360f * Utility.PhaseUpdate(Phases[TimeSeries.Pivot][b], Phases[TimeSeries.GetKey(i).Index][b]), 1f, colors[i]);

                    // UltiDraw.DrawGUICircularPivot(new Vector2(horizontal, vertical + height/4f), height/4f, UltiDraw.DarkGrey, 360f*Values[TimeSeries.GetKey(i).Index][b], 1f, UltiDraw.Cyan);
                    // Vector2 phase = Utility.PhaseVectorUpdate(Vectors[TimeSeries.Pivot][b], Vectors[TimeSeries.GetKey(i).Index][b]);
                    // UltiDraw.DrawGUICircularPivot(new Vector2(horizontal, vertical + height/4f), height/4f, UltiDraw.DarkGrey, -Vector2.SignedAngle(Vector2.up, phase), 1f, colors[i]);
                }
            }

            // //This is phase rendering
            // for(int b=0; b<Bones.Length; b++) {
            //  float w = (float)b/(float)(Bones.Length-1);
            //  float[] values = new float[TimeSeries.KeyCount];
            //  Color[] colors = new Color[TimeSeries.KeyCount];
            //  for(int i=0; i<TimeSeries.KeyCount; i++) {
            //      values[i] = Values[TimeSeries.GetKey(i).Index][b];
            //      colors[i] = UltiDraw.White.Transparent(Mathf.Clamp(Magnitudes[TimeSeries.GetKey(i).Index][b], 0f, 1f));
            //  }
            //  float vertical = Utility.Normalise(w, 0f, 1f, yMin, yMax);
            //  float height = 0.95f*(yMax-yMin)/(Bones.Length-1);
            //  UltiDraw.DrawGUIBars(new Vector2(0.5f * (xMin + xMax), vertical), new Vector2(xMax-xMin, height), values, 01f, 1f, 0.01f, UltiDraw.DarkGrey, colors);
            //  UltiDraw.DrawGUICircularPivot(new Vector2(xMax + height/2f, vertical), height/2f, UltiDraw.DarkGrey, 360f*Values[TimeSeries.Pivot][b], 1f, UltiDraw.Cyan);
            // }

            //This is energy rendering
            // for(int b=0; b<Bones.Length; b++) {
            //  float w = (float)b/(float)(Bones.Length-1);
            //  float[] values = new float[TimeSeries.KeyCount];
            //  Color[] colors = new Color[TimeSeries.KeyCount];
            //  for(int i=0; i<TimeSeries.KeyCount; i++) {
            //      values[i] = 1f;
            //      float weight = Vector2.Angle(Vector2.up, Utility.PhaseVector(Values[TimeSeries.GetKey(i).Index][b])) / 180f;
            //      colors[i] = Color.Lerp(UltiDraw.Cyan, UltiDraw.Orange, weight).Transparent(Mathf.Clamp(Magnitudes[TimeSeries.GetKey(i).Index][b], 0f, 1f));
            //  }
            //  float vertical = Utility.Normalise(w, 0f, 1f, yMin, yMax);
            //  float height = 0.95f*(yMax-yMin)/(Bones.Length-1);
            //  UltiDraw.DrawGUIBars(new Vector2(0.5f * (xMin + xMax), vertical), new Vector2(xMax-xMin, height), values, 01f, 1f, 0.01f, UltiDraw.DarkGrey, colors);
            //  UltiDraw.DrawGUICircle(new Vector2(xMax + height/2f, vertical), height/2f, colors[TimeSeries.PivotKey]);
            // }

            {
                float          max    = 0f;
                List <float[]> values = new List <float[]>();
                for (int b = 0; b < Bones.Length; b++)
                {
                    float[] v = new float[TimeSeries.KeyCount];
                    for (int i = 0; i < TimeSeries.KeyCount; i++)
                    {
                        v[i] = Magnitudes[TimeSeries.GetKey(i).Index][b];
                        max  = Mathf.Max(max, v[i]);
                    }
                    values.Add(v);
                }
                float vertical = yMin - 1f * (yMax - yMin) / (Bones.Length - 1);
                float height   = 0.95f * (yMax - yMin) / (Bones.Length - 1);
                UltiDraw.DrawGUIFunctions(new Vector2(0.5f * (xMin + xMax), vertical), new Vector2(xMax - xMin, height), values, 0f, Mathf.Max(1f, max), UltiDraw.DarkGrey, UltiDraw.GetRainbowColors(values.Count));
            }

            //This is vector rendering
            // for(int b=0; b<Bones.Length; b++) {
            //  float w = (float)b/(float)(Bones.Length-1);
            //  float[] values = new float[TimeSeries.KeyCount];
            //  Color[] colors = new Color[TimeSeries.KeyCount];
            //  for(int i=0; i<TimeSeries.KeyCount; i++) {
            //      values[i] = Utility.PhaseValue(Vectors[TimeSeries.GetKey(i).Index][b]);
            //      colors[i] = UltiDraw.White.Transparent(Mathf.Clamp(Vectors[TimeSeries.GetKey(i).Index][b].magnitude, 0f, 1f));
            //  }
            //  float vertical = Utility.Normalise(w, 0f, 1f, yMin, yMax);
            //  float height = 0.95f*(yMax-yMin)/(Bones.Length-1);
            //  UltiDraw.DrawGUIBars(new Vector2(0.5f * (xMin + xMax), vertical), new Vector2(xMax-xMin, height), values, 01f, 1f, 0.01f, UltiDraw.DarkGrey, colors);
            //  UltiDraw.DrawGUICircularPivot(new Vector2(xMax + height/2f, vertical), height/2f, UltiDraw.DarkGrey, 360f*Utility.PhaseValue(Vectors[TimeSeries.Pivot][b]), 1f, UltiDraw.Cyan);
            // }
            // {
            //  float max = 0f;
            //  List<float[]> values = new List<float[]>();
            //  for(int b=0; b<Bones.Length; b++) {
            //      float[] v = new float[TimeSeries.KeyCount];
            //      for(int i=0; i<TimeSeries.KeyCount; i++) {
            //          v[i] = Vectors[TimeSeries.GetKey(i).Index][b].magnitude;
            //          max = Mathf.Max(max, v[i]);
            //      }
            //      values.Add(v);
            //  }
            //  float vertical = yMin - 1*(yMax-yMin)/(Bones.Length-1);
            //  float height = 0.95f*(yMax-yMin)/(Bones.Length-1);
            //  UltiDraw.DrawGUIFunctions(new Vector2(0.5f * (xMin + xMax), vertical), new Vector2(xMax-xMin, height), values, 0f, Mathf.Max(2f, max), UltiDraw.DarkGrey, UltiDraw.GetRainbowColors(values.Count));
            // }
            // {
            //  List<float[]> values = new List<float[]>();
            //  for(int b=0; b<Bones.Length; b++) {
            //      float[] v = new float[TimeSeries.KeyCount];
            //      for(int i=0; i<TimeSeries.KeyCount; i++) {
            //          v[i] = Frequencies[TimeSeries.GetKey(i).Index][b];
            //      }
            //      values.Add(v);
            //  }
            //  float vertical = yMin - 2*(yMax-yMin)/(Bones.Length-1);
            //  float height = 0.95f*(yMax-yMin)/(Bones.Length-1);
            //  UltiDraw.DrawGUIFunctions(new Vector2(0.5f * (xMin + xMax), vertical), new Vector2(xMax-xMin, height), values, 0f, Mathf.Max(0.5f, 2.5f), UltiDraw.DarkGrey, UltiDraw.GetRainbowColors(values.Count));
            // }

            // {
            //  float[] combination = new float[TimeSeries.KeyCount];
            //  for(int i=0; i<TimeSeries.KeyCount; i++) {
            //      combination[i] = GetAveragePhase(TimeSeries.GetKey(i).Index);
            //  }
            //  float vertical = yMin - 2f*(yMax-yMin)/(Bones.Length-1);
            //  float height = 0.95f*(yMax-yMin)/(Bones.Length-1);
            //  UltiDraw.DrawGUIBars(new Vector2(0.5f * (xMin + xMax), vertical), new Vector2(xMax-xMin, height), combination, 01f, 1f, 0.01f, UltiDraw.DarkGrey, UltiDraw.Red);
            //  UltiDraw.DrawGUICircularPivot(new Vector2(xMax + height/2f, vertical), height/2f, UltiDraw.DarkGrey, 360f*combination[TimeSeries.PivotKey], 1f, UltiDraw.DarkRed);
            // }

            /*
             * for(int i=0; i<Values.Length; i++) {
             *      float min = 0.1f;
             *      float max = 0.9f;
             *      float size = 1f * (max-min) / Values.Length;
             *      float w = (float)i/(float)(Values.Length-1);
             *      Vector2 center = new Vector2(Utility.Normalise(w, 0f, 1f, min, max), 0.1f);
             *      UltiDraw.DrawGUICircularPivot(center, size, UltiDraw.DarkGrey, Values[i] * 360f, 1f, UltiDraw.Cyan);
             * }
             *
             * for(int i=0; i<Values.Length; i++) {
             *      float min = 0.1f;
             *      float max = 0.9f;
             *      float size = 1f * (max-min) / Values.Length;
             *      float w = (float)i/(float)(Values.Length-1);
             *      Vector2 center = new Vector2(Utility.Normalise(w, 0f, 1f, min, max), 0.1f);
             *      //UltiDraw.DrawGUICircularPivot(center, size, UltiDraw.DarkGrey, -Vector2.SignedAngle(Vector2.up, Vectors[i]), 1f, UltiDraw.Cyan);
             * }
             */

            //UltiDraw.DrawGUIBars(new Vector2(0.875f, 0.510f), new Vector2(0.2f, 0.1f), Values, 01f, 1f, 0.01f, UltiDraw.DarkGrey, UltiDraw.White);

            UltiDraw.End();
        }
Ejemplo n.º 34
0
        public async Task CanIncludeTypedTimeSeries_Rollup()
        {
            using (var store = GetDocumentStore())
            {
                var raw = new RawTimeSeriesPolicy(TimeSpan.FromHours(24));

                var p1 = new TimeSeriesPolicy("By6Hours", TimeSpan.FromHours(6), raw.RetentionTime * 4);
                var p2 = new TimeSeriesPolicy("By1Day", TimeSpan.FromDays(1), raw.RetentionTime * 5);
                var p3 = new TimeSeriesPolicy("By30Minutes", TimeSpan.FromMinutes(30), raw.RetentionTime * 2);
                var p4 = new TimeSeriesPolicy("By1Hour", TimeSpan.FromMinutes(60), raw.RetentionTime * 3);

                var config = new TimeSeriesConfiguration
                {
                    Collections = new Dictionary <string, TimeSeriesCollectionConfiguration>
                    {
                        ["Users"] = new TimeSeriesCollectionConfiguration
                        {
                            RawPolicy = raw,
                            Policies  = new List <TimeSeriesPolicy>
                            {
                                p1, p2, p3, p4
                            }
                        },
                    },
                    PolicyCheckFrequency = TimeSpan.FromSeconds(1)
                };
                await store.Maintenance.SendAsync(new ConfigureTimeSeriesOperation(config));

                await store.TimeSeries.RegisterAsync <User, StockPrice>();

                var database = await Databases.GetDocumentDatabaseInstanceFor(store);

                var now        = DateTime.UtcNow;
                var nowMinutes = now.Minute;
                now = now.AddMinutes(-nowMinutes);
                database.Time.UtcDateTime = () => DateTime.UtcNow.AddMinutes(-nowMinutes);

                var baseline = now.AddDays(-12);
                var total    = TimeSpan.FromDays(12).TotalMinutes;

                using (var session = store.OpenSession())
                {
                    session.Store(new User {
                        Name = "Karmel"
                    }, "users/karmel");
                    var ts    = session.TimeSeriesFor <StockPrice>("users/karmel");
                    var entry = new StockPrice();
                    for (int i = 0; i <= total; i++)
                    {
                        entry.Open   = i;
                        entry.Close  = i + 100_000;
                        entry.High   = i + 200_000;
                        entry.Low    = i + 300_000;
                        entry.Volume = i + 400_000;
                        ts.Append(baseline.AddMinutes(i), entry, "watches/fitbit");
                    }
                    session.SaveChanges();
                }

                await database.TimeSeriesPolicyRunner.RunRollups();

                await database.TimeSeriesPolicyRunner.DoRetention();

                await TimeSeries.VerifyPolicyExecutionAsync(store, config.Collections["Users"], 12, rawName : "StockPrices");

                using (var session = store.OpenSession())
                {
                    var user = session.Query <User>()
                               .Include(x => x.IncludeTimeSeries($"StockPrices@{p1.Name}"))
                               .First();

                    // should not go to server
                    var ts  = session.TimeSeriesRollupFor <StockPrice>(user.Id, p1.Name);
                    var res = ts.Get().ToList();
                    Assert.Equal(16, res.Count);
                    Assert.Equal(1, session.Advanced.NumberOfRequests);
                }
            }
        }
 //Ingore this function
 public override TimeSeries ExtractSeries(MotionEditor editor, TimeSeries timeSeries = null)
 {
     return(null);
 }
Ejemplo n.º 36
0
 public R(TimeSeries series, int length, Color color)
 {
     this.indicator = new SmartQuant.Indicators.R(series.series, length, color);
 }
Ejemplo n.º 37
0
 public DirectionalIndicatorMaxValueProvider(TimeSeries diPlus, TimeSeries diMinus)
 {
     this.diPlus  = diPlus;
     this.diMinus = diMinus;
 }
Ejemplo n.º 38
0
        public void CalculateInventorySpace_CurrentPeriodBeforeStorageStartPeriod_AsExpected()
        {
            const double injectionRate     = 5.0;
            const double withdrawalRate    = 6.0;
            const double startingInventory = 11.0;

            const double inventoryPercentLoss = 0.03;
            const double minInventory         = 0.0;
            const double maxInventory         = 23.5;

            var storageStart  = new Day(2019, 8, 19);
            var storageEnd    = new Day(2019, 8, 28);
            var currentPeriod = new Day(2019, 8, 10);

            var storage = CmdtyStorage <Day> .Builder
                          .WithActiveTimePeriod(storageStart, storageEnd)
                          .WithConstantInjectWithdrawRange(-withdrawalRate, injectionRate)
                          .WithConstantMinInventory(minInventory)
                          .WithConstantMaxInventory(maxInventory)
                          .WithPerUnitInjectionCost(1.5)
                          .WithNoCmdtyConsumedOnInject()
                          .WithPerUnitWithdrawalCost(0.8)
                          .WithNoCmdtyConsumedOnWithdraw()
                          .WithFixedPercentCmdtyInventoryLoss(inventoryPercentLoss)
                          .WithNoInventoryCost()
                          .MustBeEmptyAtEnd()
                          .Build();

            TimeSeries <Day, InventoryRange> inventorySpace =
                StorageHelper.CalculateInventorySpace(storage, startingInventory, currentPeriod);

            int expectedInventorySpaceCount = storageEnd.OffsetFrom(storageStart);

            Assert.Equal(expectedInventorySpaceCount, inventorySpace.Count);

            double expectedInventoryLower = startingInventory * (1 - inventoryPercentLoss) - withdrawalRate;
            double expectedInventoryUpper = startingInventory * (1 - inventoryPercentLoss) + injectionRate;

            AssertInventoryRangeEqualsExpected(inventorySpace[new Day(2019, 8, 20)], expectedInventoryLower, expectedInventoryUpper);

            expectedInventoryLower = Math.Max(expectedInventoryLower * (1 - inventoryPercentLoss) - withdrawalRate, minInventory);
            expectedInventoryUpper = Math.Min(expectedInventoryUpper * (1 - inventoryPercentLoss) + injectionRate, maxInventory);
            AssertInventoryRangeEqualsExpected(inventorySpace[new Day(2019, 8, 21)], expectedInventoryLower, expectedInventoryUpper);

            expectedInventoryLower = Math.Max(expectedInventoryLower * (1 - inventoryPercentLoss) - withdrawalRate, minInventory);
            expectedInventoryUpper = Math.Min(expectedInventoryUpper * (1 - inventoryPercentLoss) + injectionRate, maxInventory);
            AssertInventoryRangeEqualsExpected(inventorySpace[new Day(2019, 8, 22)], expectedInventoryLower, expectedInventoryUpper);

            expectedInventoryLower = Math.Max(expectedInventoryLower * (1 - inventoryPercentLoss) - withdrawalRate, minInventory);
            expectedInventoryUpper = Math.Min(expectedInventoryUpper * (1 - inventoryPercentLoss) + injectionRate, maxInventory);
            AssertInventoryRangeEqualsExpected(inventorySpace[new Day(2019, 8, 23)], expectedInventoryLower, expectedInventoryUpper);

            expectedInventoryLower = Math.Max(expectedInventoryLower * (1 - inventoryPercentLoss) - withdrawalRate, minInventory);
            expectedInventoryUpper = Math.Min(expectedInventoryUpper * (1 - inventoryPercentLoss) + injectionRate, maxInventory);
            AssertInventoryRangeEqualsExpected(inventorySpace[new Day(2019, 8, 24)], expectedInventoryLower, expectedInventoryUpper);

            // At this point the backwardly derived reduced inventory space kicks in so we need to start going backwards in time
            expectedInventoryLower = 0.0;
            expectedInventoryUpper = 0.0;
            AssertInventoryRangeEqualsExpected(inventorySpace[new Day(2019, 8, 28)], expectedInventoryLower, expectedInventoryUpper);

            expectedInventoryUpper = Math.Min((expectedInventoryUpper + withdrawalRate) / (1 - inventoryPercentLoss), maxInventory);
            AssertInventoryRangeEqualsExpected(inventorySpace[new Day(2019, 8, 27)], expectedInventoryLower, expectedInventoryUpper);

            expectedInventoryUpper = Math.Min((expectedInventoryUpper + withdrawalRate) / (1 - inventoryPercentLoss), maxInventory);
            AssertInventoryRangeEqualsExpected(inventorySpace[new Day(2019, 8, 26)], expectedInventoryLower, expectedInventoryUpper);

            expectedInventoryUpper = Math.Min((expectedInventoryUpper + withdrawalRate) / (1 - inventoryPercentLoss), maxInventory);
            AssertInventoryRangeEqualsExpected(inventorySpace[new Day(2019, 8, 25)], expectedInventoryLower, expectedInventoryUpper);
        }
Ejemplo n.º 39
0
 //static Series method
 public static FourierSeries Series(TimeSeries ds, Int32 period)
 {
     return(new FourierSeries(ds, period));
 }
Ejemplo n.º 40
0
 public override ComponentSeries DerivedExtractSeries(TimeSeries global, float timestamp, bool mirrored)
 {
     return(null);
 }
Ejemplo n.º 41
0
 public FO(TimeSeries series, int length)
 {
     this.indicator = new FreeQuant.Indicators.FO(series.series, length);
 }
Ejemplo n.º 42
0
        //populate
        public override void Populate()
        {
            TimeSeries ds     = Parameters[0].AsTimeSeries;
            Int32      period = Parameters[1].AsInt;
            Double     k      = Parameters[2].AsDouble;

            DateTimes = ds.DateTimes;

            if (period <= 0 || ds.Count == 0)
            {
                return;
            }

            var halfperiod = period / 2;
            var HH         = new Highest(ds, halfperiod);
            var LL         = new Lowest(ds, halfperiod);
            var Log2       = Math.Log(2);

            //Assign first bar that contains indicator data
            var FirstValidValue = ds.FirstValidIndex + 2 * halfperiod - 1;

            if (FirstValidValue > ds.Count)
            {
                FirstValidValue = ds.Count;
            }

            //Initialize start of series
            for (int bar = 0; bar < FirstValidValue; bar++)
            {
                Values[bar] = ds[bar];
            }

            //Rest of series
            for (int bar = FirstValidValue; bar < ds.Count; bar++)
            {
                //First half
                double hh1 = HH[bar - halfperiod];
                double ll1 = LL[bar - halfperiod];
                double n1  = (hh1 - ll1) / halfperiod;

                //Second half
                double hh2 = HH[bar];
                double ll2 = LL[bar];
                double n2  = (hh2 - ll2) / halfperiod;

                //Complete interval
                double hh3 = Math.Max(hh1, hh2);
                double ll3 = Math.Min(ll1, ll2);
                double n3  = (hh3 - ll3) / (2 * halfperiod);

                //Set Dimension variable
                double n     = n1 + n2;
                double Dimen = 1;
                if (n > 0)
                {
                    Dimen = Math.Log(n / n3) / Log2;        // always less than 2
                }
                //Formula for exp. moving average
                if (Dimen < 1)
                {
                    Dimen = 1;
                }
                double alpha = Math.Exp(-k * (Dimen - 1));

                Values[bar] = alpha * ds[bar] + (1 - alpha) * Values[bar - 1];
            }
        }
Ejemplo n.º 43
0
 public MACD(TimeSeries series, int length1, int length2, Color color)
 {
     this.indicator = new SmartQuant.Indicators.MACD(series.series, length1, length2, color);
 }
Ejemplo n.º 44
0
 public TRIX(TimeSeries input, int length) :  base(input)
 {
     this.fLength = 14;
     this.fLength = length;
     this.Init();
 }
Ejemplo n.º 45
0
        public void CalculateInventorySpace_CurrentPeriodAfterStorageStartPeriod_AsExpected()
        {
            const double injectionRate     = 5.0;
            const double withdrawalRate    = 6.0;
            const double startingInventory = 8.0;

            const double inventoryPercentLoss = 0.03;
            const double minInventory         = 0.0;
            const double maxInventory         = 23.5;

            var storageStart  = new Day(2019, 8, 1);
            var storageEnd    = new Day(2019, 8, 28);
            var currentPeriod = new Day(2019, 8, 20);

            var storage = CmdtyStorage <Day> .Builder
                          .WithActiveTimePeriod(storageStart, storageEnd)
                          .WithConstantInjectWithdrawRange(-withdrawalRate, injectionRate)
                          .WithConstantMinInventory(minInventory)
                          .WithConstantMaxInventory(maxInventory)
                          .WithPerUnitInjectionCost(1.5)
                          .WithNoCmdtyConsumedOnInject()
                          .WithPerUnitWithdrawalCost(0.8)
                          .WithNoCmdtyConsumedOnWithdraw()
                          .WithFixedPercentCmdtyInventoryLoss(inventoryPercentLoss)
                          .WithNoInventoryCost()
                          .WithTerminalInventoryNpv((cmdtyPrice, inventory) => 0.0)
                          .Build();

            TimeSeries <Day, InventoryRange> inventorySpace =
                StorageHelper.CalculateInventorySpace(storage, startingInventory, currentPeriod);

            int expectedInventorySpaceCount = storageEnd.OffsetFrom(currentPeriod);

            Assert.Equal(expectedInventorySpaceCount, inventorySpace.Count);

            double expectedInventoryLower = startingInventory * (1 - inventoryPercentLoss) - withdrawalRate;
            double expectedInventoryUpper = startingInventory * (1 - inventoryPercentLoss) + injectionRate;

            AssertInventoryRangeEqualsExpected(inventorySpace[new Day(2019, 8, 21)], expectedInventoryLower, expectedInventoryUpper);

            expectedInventoryLower = Math.Max(expectedInventoryLower * (1 - inventoryPercentLoss) - withdrawalRate, minInventory);
            expectedInventoryUpper = Math.Min(expectedInventoryUpper * (1 - inventoryPercentLoss) + injectionRate, maxInventory);
            AssertInventoryRangeEqualsExpected(inventorySpace[new Day(2019, 8, 22)], expectedInventoryLower, expectedInventoryUpper);

            expectedInventoryLower = Math.Max(expectedInventoryLower * (1 - inventoryPercentLoss) - withdrawalRate, minInventory);
            expectedInventoryUpper = Math.Min(expectedInventoryUpper * (1 - inventoryPercentLoss) + injectionRate, maxInventory);
            AssertInventoryRangeEqualsExpected(inventorySpace[new Day(2019, 8, 23)], expectedInventoryLower, expectedInventoryUpper);

            expectedInventoryLower = Math.Max(expectedInventoryLower * (1 - inventoryPercentLoss) - withdrawalRate, minInventory);
            expectedInventoryUpper = Math.Min(expectedInventoryUpper * (1 - inventoryPercentLoss) + injectionRate, maxInventory);
            AssertInventoryRangeEqualsExpected(inventorySpace[new Day(2019, 8, 24)], expectedInventoryLower, expectedInventoryUpper);

            expectedInventoryLower = Math.Max(expectedInventoryLower * (1 - inventoryPercentLoss) - withdrawalRate, minInventory);
            expectedInventoryUpper = Math.Min(expectedInventoryUpper * (1 - inventoryPercentLoss) + injectionRate, maxInventory);
            AssertInventoryRangeEqualsExpected(inventorySpace[new Day(2019, 8, 25)], expectedInventoryLower, expectedInventoryUpper);

            expectedInventoryLower = Math.Max(expectedInventoryLower * (1 - inventoryPercentLoss) - withdrawalRate, minInventory);
            expectedInventoryUpper = Math.Min(expectedInventoryUpper * (1 - inventoryPercentLoss) + injectionRate, maxInventory);
            AssertInventoryRangeEqualsExpected(inventorySpace[new Day(2019, 8, 26)], expectedInventoryLower, expectedInventoryUpper);

            expectedInventoryLower = Math.Max(expectedInventoryLower * (1 - inventoryPercentLoss) - withdrawalRate, minInventory);
            expectedInventoryUpper = Math.Min(expectedInventoryUpper * (1 - inventoryPercentLoss) + injectionRate, maxInventory);
            AssertInventoryRangeEqualsExpected(inventorySpace[new Day(2019, 8, 27)], expectedInventoryLower, expectedInventoryUpper);

            expectedInventoryLower = Math.Max(expectedInventoryLower * (1 - inventoryPercentLoss) - withdrawalRate, minInventory);
            expectedInventoryUpper = Math.Min(expectedInventoryUpper * (1 - inventoryPercentLoss) + injectionRate, maxInventory);
            AssertInventoryRangeEqualsExpected(inventorySpace[new Day(2019, 8, 28)], expectedInventoryLower, expectedInventoryUpper);
        }
Ejemplo n.º 46
0
 public WilliamsRIndicator(TimeSeries timeSeries, int timeFrame) : this(new ClosePriceIndicator(timeSeries), timeFrame, new MaxPriceIndicator(timeSeries), new MinPriceIndicator(timeSeries))
 {
 }
Ejemplo n.º 47
0
        public override void Recompute()
        {
            IsValid = false;

            tsOutput   = null;
            mvtsOutput = null;

            // make sure we have at least 2 data points in the time series to be sampled
            var tp = GetInputType(0);

            if (tp != InputType.UnivariateTS && tp != InputType.MultivariateTS)
            {
                return;
            }
            var rp = GetInputType(1);

            if (rp != InputType.UnivariateTS && rp != InputType.MultivariateTS)
            {
                return;
            }

            // first get the reference times
            var times  = new List <DateTime>(1000);
            var input1 = GetInput(1);
            var mvref  = input1 as MVTimeSeries;
            var uref   = input1 as TimeSeries;

            if (rp == InputType.UnivariateTS)
            {
                if (uref == null)
                {
                    return;
                }
                for (int t = 0; t < uref.Count; ++t)
                {
                    times.Add(uref.TimeStamp(t));
                }
            }
            else if (rp == InputType.MultivariateTS)
            {
                if (mvref == null)
                {
                    return;
                }
                for (int t = 0; t < mvref.Count; ++t)
                {
                    times.Add(mvref.TimeStamp(t));
                }
            }
            else
            {
                throw new ApplicationException("Invalid input type; this should not happen!");
            }
            int refDim = uref != null ? 1 : mvref.Dimension;

            // then sample to get the output
            if (tp == InputType.UnivariateTS)
            {
                var uts = GetInput(0) as TimeSeries;
                if (uts == null)
                {
                    return;
                }

                // split it up
                if (!IncludeReferenceInOutput)
                {
                    tsOutput = new TimeSeries();
                    for (int t = 0; t < times.Count; ++t)
                    {
                        tsOutput.Add(times[t], uts.ValueAtTime(times[t]), true);
                    }
                }
                else
                {
                    mvtsOutput = new MVTimeSeries(1 + refDim);
                    for (int t = 0; t < times.Count; ++t)
                    {
                        var val = new double[1 + refDim];
                        val[0] = uts.ValueAtTime(times[t]);
                        for (int i = 1; i <= refDim; ++i)
                        {
                            val[i] = mvref != null ? mvref[t][i - 1] : uref[t];
                        }
                        mvtsOutput.Add(times[t], val, true);
                    }
                }
                IsValid = true;
            }
            if (tp == InputType.MultivariateTS)
            {
                var mts = GetInput(0) as MVTimeSeries;
                if (mts == null)
                {
                    return;
                }

                // split it up
                if (!IncludeReferenceInOutput)
                {
                    mvtsOutput = new MVTimeSeries();
                    for (int t = 0; t < times.Count; ++t)
                    {
                        mvtsOutput.Add(times[t], mts.ValueAtTime(times[t]), true);
                    }
                }
                else
                {
                    int thisDim = mts.Dimension;
                    mvtsOutput = new MVTimeSeries(thisDim + refDim);
                    for (int t = 0; t < times.Count; ++t)
                    {
                        var val = new double[thisDim + refDim];
                        var dv  = mts.ValueAtTime(times[t]);
                        for (int i = 0; i < thisDim; ++i)
                        {
                            val[i] = dv[i];
                        }
                        for (int i = 0; i < refDim; ++i)
                        {
                            val[i + thisDim] = mvref != null ? mvref[t][i] : uref[t];
                        }
                        mvtsOutput.Add(times[t], val, true);
                    }
                }
                IsValid = true;
            }
        }
Ejemplo n.º 48
0
        public async Task <IAggregatedEvent> GetArtistAggregatedEventAsync(int id, TimeSeries timeSeries)
        {
            IAggregatedEvent aggregatedEvent = await _artistTimeSeriesCache.FetchTimeSeriesAggregatedEventAsync(id, timeSeries);

            return(aggregatedEvent);
        }
Ejemplo n.º 49
0
        //populate
        public override void Populate()
        {
            TimeSeries ds     = Parameters[0].AsTimeSeries;
            Int32      period = Parameters[1].AsInt;

            DateTimes = ds.DateTimes;

            int FirstValidValue = period + 2;

            if (period <= 0 || ds.Count < FirstValidValue)
            {
                return;
            }

            double     Bandwidth = 0.1;
            double     G1 = 0, S1 = 0, L1 = 0, G2 = 0, S2 = 0, L2 = 0, G3 = 0, S3 = 0, L3 = 0;
            TimeSeries BP1 = new TimeSeries(DateTimes), BP2 = new TimeSeries(DateTimes), BP3 = new TimeSeries(DateTimes),
                       Q1 = new TimeSeries(DateTimes), Q2 = new TimeSeries(DateTimes), Q3 = new TimeSeries(DateTimes),
                       P1 = new TimeSeries(DateTimes), P2 = new TimeSeries(DateTimes), P3 = new TimeSeries(DateTimes);
            double Deg2Rad = Math.PI / 180.0;

            BP1.Description = string.Format("BP1({0},{1})", ds, period);
            BP2.Description = string.Format("BP2({0},{1})", ds, period);
            BP3.Description = string.Format("BP3({0},{1})", ds, period);

            Q1.Description = string.Format("Q1({0},{1})", ds, period);
            Q2.Description = string.Format("Q2({0},{1})", ds, period);
            Q3.Description = string.Format("Q3({0},{1})", ds, period);

            P1.Description = string.Format("P1({0},{1})", ds, period);
            P2.Description = string.Format("P2({0},{1})", ds, period);
            P3.Description = string.Format("P3({0},{1})", ds, period);

            //compute filter coefficients once
            L1 = Math.Cos(360d / period * Deg2Rad);
            G1 = Math.Cos(Bandwidth * 360 / period * Deg2Rad);
            S1 = 1d / G1 - Math.Sqrt(1d / (G1 * G1) - 1);
            L2 = Math.Cos(360d / (period / 2d) * Deg2Rad);
            G2 = Math.Cos(Bandwidth * 360 / (period / 2d) * Deg2Rad);
            S2 = 1d / G2 - Math.Sqrt(1d / (G2 * G2) - 1);
            L3 = Math.Cos(360 / (period / 3d) * Deg2Rad);
            G3 = Math.Cos(Bandwidth * 360 / (period / 3d) * Deg2Rad);
            S3 = 1d / G3 - Math.Sqrt(1d / (G3 * G3) - 1);

            for (int i = 0; i < FirstValidValue; i++)
            {
                BP1[i] = BP2[i] = BP3[i] = 0;
                Q1[i]  = Q2[i] = Q3[i] = 0;
                P1[i]  = P2[i] = P3[i] = 0;
            }

            for (int bar = FirstValidValue; bar < ds.Count; bar++)
            {
                //Fundamental Band-Pass
                if (bar >= 2)
                {
                    BP1[bar] = .5 * (1 - S1) * (ds[bar] - ds[bar - 2]) + L1 * (1 + S1) * BP1[bar - 1] - S1 * BP1[bar - 2];
                }
                if (bar <= 3)
                {
                    BP1[bar] = 0;
                    BP2[bar] = 0;
                    BP3[bar] = 0;
                }
                //Fundamental Quadrature
                if (bar >= 1)
                {
                    Q1[bar] = (period / 6.28) * (BP1[bar] - BP1[bar - 1]);
                }
                if (bar <= 4)
                {
                    Q1[bar] = 0;
                    Q2[bar] = 0;
                    Q3[bar] = 0;
                }

                //Second Harmonic Band-Pass
                if (bar >= 2)
                {
                    BP2[bar] = .5 * (1 - S2) * (ds[bar] - ds[bar - 2]) + L2 * (1 + S2) * BP2[bar - 1] - S2 * BP2[bar - 2];
                }

                //Second Harmonic Quadrature
                if (bar >= 1)
                {
                    Q2[bar] = (period / 6.28) * (BP2[bar] - BP2[bar - 1]);
                }

                //Third Harmonic Band-Pass
                if (bar >= 2)
                {
                    BP3[bar] = .5 * (1 - S3) * (ds[bar] - ds[bar - 2]) + L3 * (1 + S3) * BP3[bar - 1] - S3 * BP3[bar - 2];
                }

                //Third Harmonic Quadrature
                if (bar >= 1)
                {
                    Q3[bar] = (period / 6.28) * (BP3[bar] - BP3[bar - 1]);
                }

                //Sum power of each harmonic at each bar over the Fundamental period
                P1[bar] = 0;
                P2[bar] = 0;
                P3[bar] = 0;
                for (int count = 0; count < period; count++)
                {
                    P1[bar] = P1[bar] + BP1[bar - count] * BP1[bar - count] + Q1[bar - count] * Q1[bar - count];
                    P2[bar] = P2[bar] + BP2[bar - count] * BP2[bar - count] + Q2[bar - count] * Q2[bar - count];
                    P3[bar] = P3[bar] + BP3[bar - count] * BP3[bar - count] + Q3[bar - count] * Q3[bar - count];
                }

                //Add the three harmonics together using their relative amplitudes
                if (P1[bar] != 0)
                {
                    Values[bar] = BP1[bar] + Math.Sqrt(P2[bar] / P1[bar]) * BP2[bar] + Math.Sqrt(P3[bar] / P1[bar]) * BP3[bar];
                }
            }
        }
        private List <TimeSeriesPoint> LoadPointsFrom3X(IAquariusClient client)
        {
            var timeSeriesDescription = client.Publish.Get(new Get3xTimeSeriesDescription
            {
                LocationIdentifier = Context.SourceTimeSeries.LocationIdentifier,
                Parameter          = Context.SourceTimeSeries.Parameter
            })
                                        .TimeSeriesDescriptions
                                        .SingleOrDefault(ts => ts.Identifier == Context.SourceTimeSeries.TargetIdentifier);

            if (timeSeriesDescription == null)
            {
                throw new ExpectedException($"Can't find '{Context.SourceTimeSeries.Identifier}' time-series in location '{Context.SourceTimeSeries.LocationIdentifier}'.");
            }

            Log.Info($"Loading points from '{timeSeriesDescription.Identifier}' ...");

            var correctedData = client.Publish.Get(new Get3xCorrectedData
            {
                TimeSeriesIdentifier = Context.SourceTimeSeries.Identifier,
                QueryFrom            = Context.SourceQueryFrom?.ToDateTimeOffset(),
                QueryTo = Context.SourceQueryTo?.ToDateTimeOffset()
            });

            var points = correctedData
                         .Points
                         .Select(p => new TimeSeriesPoint
            {
                Time      = Instant.FromDateTimeOffset(p.Timestamp),
                Value     = p.Value,
                GradeCode = p.Grade
            })
                         .ToList();

            // 3.X Publish API's TimeSeriesDescription is missing some info, so grab those pieces from elsewhere

            // The time-range start will always be in the offset of the time-series, even when no points exist
            var utcOffset = Offset.FromHoursAndMinutes(correctedData.TimeRange.StartTime.Offset.Hours, correctedData.TimeRange.StartTime.Offset.Minutes);

            // We can infer the interpolationType from the last point (if one exists)
            var interpolationType = Context.InterpolationType ?? (correctedData.Points.Any()
                                        ? (InterpolationType?)correctedData.Points.Last().Interpolation
                                        : null);

            var timeSeries = new TimeSeries
            {
                Identifier                  = Context.SourceTimeSeries.Identifier,
                Parameter                   = timeSeriesDescription.Parameter,
                Label                       = timeSeriesDescription.Label,
                Unit                        = timeSeriesDescription.Unit,
                Publish                     = timeSeriesDescription.Publish,
                Description                 = timeSeriesDescription.Description,
                Comment                     = timeSeriesDescription.Comment,
                TimeSeriesType              = KnownTimeSeriesTypes[timeSeriesDescription.TimeSeriesType],
                UtcOffset                   = utcOffset,
                ComputationIdentifier       = timeSeriesDescription.ComputationIdentifier,
                ComputationPeriodIdentifier = timeSeriesDescription.ComputationPeriodIdentifier,
                SubLocationIdentifier       = timeSeriesDescription.SubLocationIdentifier,
                LocationIdentifier          = timeSeriesDescription.LocationIdentifier,
                ExtendedAttributeValues     = timeSeriesDescription.ExtendedAttributes.Select(ea =>
                                                                                              new ExtendedAttributeValue
                {
                    ColumnIdentifier = $"{ea.Name.ToUpperInvariant()}@TIMESERIES_EXTENSION",
                    Value            = ea.Value?.ToString()
                })
                                              .ToList()
            };

            SetTimeSeriesCreationProperties(timeSeries, interpolationType: interpolationType);

            if (!Context.IgnoreNotes)
            {
                var corrections = client.Publish.Get(new Get3xCorrectionList
                {
                    TimeSeriesIdentifier = Context.SourceTimeSeries.Identifier,
                    QueryFrom            = Context.SourceQueryFrom?.ToDateTimeOffset(),
                    QueryTo = Context.SourceQueryTo?.ToDateTimeOffset()
                }).Corrections;

                var utcTimespan = utcOffset.ToTimeSpan();
                Notes.AddRange(corrections.Select(c => Convert3XCorrection(utcTimespan, c)));
            }

            Log.Info($"Loaded {PointSummarizer.Summarize(points)} and {"note".ToQuantity(Notes.Count)} from {Context.SourceTimeSeries.Identifier}");

            return(points);
        }
Ejemplo n.º 51
0
 public SlimTimeSeries(TimeSeriesLink link, TimeSeries source) : base(link, source)
 {
     Values = source.ToArray();
 }
Ejemplo n.º 52
0
        public static string GetIsoDateTimeStringStart(TimeSeries timeSeries)
        {
            var d = timeSeries.Start;

            return(d.ToString(IsoDateTime.DATE_WHITESPACE_TIME_FORMAT_TO_SECOND, CultureInfo.InvariantCulture));
        }
Ejemplo n.º 53
0
 public Phase(TimeSeries timeSeries)
 {
     timeSeries.Add(this);
     Values = new float[TimeSeries.Samples.Length];
 }
Ejemplo n.º 54
0
 public MaxPriceIndicator(TimeSeries series) : base(series)
 {
     _series = series;
 }
Ejemplo n.º 55
0
 public ParabolicSarIndicator(TimeSeries series, int timeFrame) : base(series)
 {
     _series = series;
     _lowestValueIndicator  = new LowestValueIndicator(new MinPriceIndicator(series), timeFrame);
     _highestValueIndicator = new HighestValueIndicator(new MaxPriceIndicator(series), timeFrame);
 }
Ejemplo n.º 56
0
 public CandleQuantityDiPlusVsDiMinusProvider(TimeSeries diPlus, TimeSeries diMinus)
 {
     this.diPlus  = diPlus;
     this.diMinus = diMinus;
 }
Ejemplo n.º 57
0
        public async Task CanIndexRollups()
        {
            using (var store = GetDocumentStore())
            {
                var raw = new RawTimeSeriesPolicy(TimeValue.FromHours(24));

                var p1 = new TimeSeriesPolicy("By6Hours", TimeValue.FromHours(6), raw.RetentionTime * 4);
                var p2 = new TimeSeriesPolicy("By1Day", TimeValue.FromDays(1), raw.RetentionTime * 5);
                var p3 = new TimeSeriesPolicy("By30Minutes", TimeValue.FromMinutes(30), raw.RetentionTime * 2);
                var p4 = new TimeSeriesPolicy("By1Hour", TimeValue.FromMinutes(60), raw.RetentionTime * 3);

                var config = new TimeSeriesConfiguration
                {
                    Collections = new Dictionary <string, TimeSeriesCollectionConfiguration>
                    {
                        ["Users"] = new TimeSeriesCollectionConfiguration
                        {
                            RawPolicy = raw,
                            Policies  = new List <TimeSeriesPolicy>
                            {
                                p1, p2, p3, p4
                            }
                        },
                    },
                    PolicyCheckFrequency = TimeSpan.FromSeconds(1)
                };
                await store.Maintenance.SendAsync(new ConfigureTimeSeriesOperation(config));

                var database = await Databases.GetDocumentDatabaseInstanceFor(store);

                var now        = DateTime.UtcNow;
                var nowSeconds = now.Second;
                now = now.AddSeconds(-nowSeconds);
                database.Time.UtcDateTime = () => DateTime.UtcNow.AddSeconds(-nowSeconds);

                var baseline = now.AddDays(-12);
                var total    = ((TimeSpan)TimeValue.FromDays(12)).TotalMinutes;

                await new TimeSeriesIndex().ExecuteAsync(store);

                using (var session = store.OpenSession())
                {
                    session.Store(new User {
                        Name = "Karmel"
                    }, "users/karmel");
                    for (int i = 0; i <= total; i++)
                    {
                        session.TimeSeriesFor("users/karmel", "Heartrate")
                        .Append(baseline.AddMinutes(i), new[] { 29d * i, i }, "watches/fitbit");
                    }
                    session.SaveChanges();
                }

                await TimeSeries.WaitForPolicyRunnerAsync(database);

                await TimeSeries.VerifyPolicyExecutionAsync(store, config.Collections["Users"], 4, policies : new List <TimeSeriesPolicy> {
                    p1
                });

                await TimeSeries.VerifyPolicyExecutionAsync(store, config.Collections["Users"], 5, policies : new List <TimeSeriesPolicy> {
                    p2
                });

                await TimeSeries.VerifyPolicyExecutionAsync(store, config.Collections["Users"], 2, policies : new List <TimeSeriesPolicy> {
                    p3
                });

                await TimeSeries.VerifyPolicyExecutionAsync(store, config.Collections["Users"], 3, policies : new List <TimeSeriesPolicy> {
                    p4
                });

                Indexes.WaitForIndexing(store);
                RavenTestHelper.AssertNoIndexErrors(store);

                using (var session = store.OpenSession())
                {
                    var user = session.Load <User>("users/karmel");

                    var count = session
                                .TimeSeriesFor(user, "Heartrate")
                                .Get(DateTime.MinValue, DateTime.MaxValue)
                                .Count(entry => entry.IsRollup == false);

                    count += session
                             .TimeSeriesFor(user, "Heartrate@By6Hours")
                             .Get(DateTime.MinValue, DateTime.MaxValue)
                             .Count();

                    count += session
                             .TimeSeriesFor(user, "Heartrate@By1Day")
                             .Get(DateTime.MinValue, DateTime.MaxValue)
                             .Count();

                    count += session
                             .TimeSeriesFor(user, "Heartrate@By30Minutes")
                             .Get(DateTime.MinValue, DateTime.MaxValue)
                             .Count();

                    count += session
                             .TimeSeriesFor(user, "Heartrate@By1Hour")
                             .Get(DateTime.MinValue, DateTime.MaxValue)
                             .Count();

                    var results = session.Query <TimeSeriesIndex.Result, TimeSeriesIndex>()
                                  .ToList();

                    Assert.True(count == results.Count, $"Test time = {now}");
                }
            }
        }
Ejemplo n.º 58
0
 public void SetUp()
 {
     _mockdata   = GenerateTimeSeries.From(29.49, 28.30, 27.74, 27.65, 27.60, 28.70, 28.60, 28.19, 27.40, 27.20, 27.28, 27.00, 27.59, 26.20, 25.75, 24.75, 23.33, 24.45, 24.25, 25.02, 23.60, 24.20, 24.28, 25.70, 25.46, 25.10, 25.00, 25.00, 25.85);
     _closePrice = new ClosePriceIndicator(_mockdata);
 }
Ejemplo n.º 59
0
 public MOM(TimeSeries series, int length)
 {
     this.indicator = new SmartQuant.Indicators.MOM(series.series, length);
 }
Ejemplo n.º 60
0
 public void SetUp()
 {
     _timeSeries      = GenerateTimeSeries.WithArbitraryTicks();
     _amountIndicator = new AmountIndicator(_timeSeries);
 }