public void TestCalculateRealData()
        {
            TickerBLL tbll = new TickerBLL(_unit);

            List <Ticker> tList = tbll.GetTickerListByShareDB(1585, null, 21100000);

            double[] inputData = new double[tList.Count];
            double[] h         = new double[tList.Count];
            double[] lo        = new double[tList.Count];

            double?[] k = new double?[tList.Count];
            double?[] d = new double?[tList.Count];
            var       i = 0;

            foreach (var t in tList)
            {
                inputData[i] = t.Close;
                h[i]         = t.High;
                lo[i]        = t.Low;

                i++;
            }


            Result res = Stochastic.CalculateSlow(inputData, h, lo, 14, 3, k, d);
        }
Пример #2
0
        /// <summary>
        /// Реализация эксперимента
        /// </summary>
        public void CalcExper()
        {
            double minI = 0.2, maxI = 1.2;
            double minQ = 3, maxQ = 10;
            int    step = 3, nExp = 100;

            TextWriter tw = new StreamWriter("res.txt");

            for (double i = minI; i <= maxI; i += (maxI - minI) / step)
            {
                for (double q = minQ; q <= maxQ; q += (maxQ - minQ) / step)
                {
                    for (int j = 0; j < nExp; j++)
                    {
                        this.sI = new Stochastic(dl: 2, scl: i);
                        this.sQ = new Stochastic(dl: 1, loc: q, scl: q / 5);

                        double[] sc = new double[4];
                        while (sc[0] <= 0 || double.IsPositiveInfinity(sc[0]))
                        {
                            sc = simplexCoeffs();
                        }

                        tw.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}", i, q, sc[0], sc[1], sc[3]);
                        //tw.WriteLine("{0}\t{1}\t{2}", i, q, SimulateTS());
                    }
                }
            }
            tw.Close();
        }
        public void TestCalculate()
        {
            double[] high = new double[] {
                127.01, 127.62, 126.59, 127.35, 128.17,
                128.43, 127.37, 126.42, 126.90, 126.85,
                125.65, 125.72, 127.16, 127.72, 127.69,
                128.22, 128.27, 128.09, 128.27, 127.74,
                128.77, 129.29, 130.06, 129.12, 129.29,
                128.47, 128.09, 128.65, 129.14, 128.64
            };

            double[] low = new double[] {
                125.36, 126.16, 124.93, 126.09, 126.82,
                126.48, 126.03, 124.83, 126.39, 125.72,
                124.56, 124.57, 125.07, 126.86, 126.63,
                126.80, 126.71, 126.80, 126.13, 125.92,
                126.99, 127.81, 128.47, 128.06, 127.61,
                127.60, 127.00, 126.90, 127.49, 127.40
            };

            double[] close = new double[] {
                0, 0, 0, 0, 0,
                0, 0, 0, 0, 0,
                0, 0, 0, 127.29, 127.18,
                128.01, 127.11, 127.73, 127.06, 127.33,
                128.71, 127.87, 128.58, 128.60, 127.93,
                128.11, 127.60, 127.60, 128.69, 128.27
            };

            double?[] k = new double?[close.Length];
            double?[] d = new double?[close.Length];


            Stochastic.CalculateSlow(close, high, low, 14, 3, k, d);
        }
Пример #4
0
        public override void GetAll(IIndicatorValues Ind)
        {
            int     period = (int)this.IndicatorParameters.List[0];
            int     firstSmoothingPeriod  = (int)this.IndicatorParameters.List[1];
            int     secondSmoothingPeriod = (int)this.IndicatorParameters.List[2];
            decimal thresholdPercentage   = (decimal)this.IndicatorParameters.List[3];

            if (!Ind.SlowStochastic(period, firstSmoothingPeriod, secondSmoothingPeriod, thresholdPercentage).IsPopulated)
            {
                int oldCurrentBar = Ind.Bar.CurrentBar;
                for (int i = 1; i <= Ind.Bar.MaxBar; i++)
                {
                    Ind.Bar.CurrentBar = i;

                    object prototype = null;
                    if (i == 1)
                    {
                        prototype = new Stochastic(thresholdPercentage);
                    }
                    else
                    {
                        prototype = (Stochastic)Ind.SlowStochastic(period, firstSmoothingPeriod, secondSmoothingPeriod, thresholdPercentage)[1].Clone();
                    }

                    Get(ref prototype, Ind);

                    Ind.SlowStochastic(period, firstSmoothingPeriod, secondSmoothingPeriod, thresholdPercentage)[0] = (Stochastic)prototype;

                    Ind.SlowStochastic(period, firstSmoothingPeriod, secondSmoothingPeriod, thresholdPercentage).IsPopulated = true;                     // set here so instance is guaranteed to exits
                }

                Ind.Bar.CurrentBar = oldCurrentBar;
            }
        }
Пример #5
0
        public void PrimaryOutputIsFastStochProperty()
        {
            var stochastics = new Stochastic("sto", 12, 3, 5);

            TestHelper.TestIndicator(stochastics, "spy_with_stoch12k3.txt", "Stochastics 12 %K 3",
                                     (ind, expected) => Assert.Equal(((Stochastic)ind).FastStoch.Current.Price, ind.Current.Price));
        }
Пример #6
0
        public async Task<IndStochasticEntity[]> GetStochastic(string code, int period = 14, int slow =3, int start = 0, int end = 0, string type = "day")
        {
            TickerEntity[] tickers = await base.getTickerEntityArray(code, start, end, type);
            List<IndStochasticEntity> outList = new List<IndStochasticEntity>();

            int len = tickers.Length;

            double[] close = tickers.Select(t => (double)t.C).ToArray();
            double[] high = tickers.Select(t => (double)t.H).ToArray();
            double[] low = tickers.Select(t => (double)t.L).ToArray();

            double?[] outK = new double?[len];
            double?[] outD = new double?[len];

            Stochastic.CalculateSlow(close, high, low, period, slow, outK, outD);

            for (int i = 0; i < len; i++)
            {
                outList.Add(new IndStochasticEntity
                {
                    T = tickers[i].T,
                    P = tickers[i].P,
                    K = outK[i],
                    D = outD[i]
                });
            }

            return outList.Where(r => (start == 0 || r.P >= start) && (end == 0 || r.P <= end)).ToArray();
        }
Пример #7
0
        /// <summary>
        /// Creates a new Stochastic indicator.
        /// </summary>
        /// <param name="symbol">The symbol whose stochastic we seek</param>
        /// <param name="resolution">The resolution.</param>
        /// <param name="period">The period of the stochastic. Normally 14</param>
        /// <param name="kPeriod">The sum period of the stochastic. Normally 14</param>
        /// <param name="dPeriod">The sum period of the stochastic. Normally 3</param>
        /// <returns>Stochastic indicator for the requested symbol.</returns>
        public Stochastic STO(string symbol, int period, int kPeriod, int dPeriod, Resolution?resolution = null)
        {
            string name  = CreateIndicatorName(symbol, "STO", resolution);
            var    stoch = new Stochastic(name, period, kPeriod, dPeriod);

            RegisterIndicator(symbol, stoch, resolution);
            return(stoch);
        }
Пример #8
0
        public void ComparesAgainstExternalDataOnStochasticsK()
        {
            var stochastics = new Stochastic("sto", 12, 3, 5);

            const double epsilon = 1e-3;

            TestHelper.TestIndicator(stochastics, "spy_with_stoch12k3.txt", "Stochastics 12 %K 3",
                                     (ind, expected) => ((double)((Stochastic)ind).StochK.Current.Price).Should()
                                     .BeApproximately(expected, epsilon));
        }
 protected override void Create()
 {
     m_Stochastic = new Stochastic(this);
     m_oFastK     = new VariableSeries <Double>(this);
     m_oFastD     = new VariableSeries <Double>(this);
     m_oSlowK     = new VariableSeries <Double>(this);
     m_oSlowD     = new VariableSeries <Double>(this);
     m_StochLE    =
         OrderCreator.MarketNextBar(new SOrderParameters(Contracts.Default, "StochLE", EOrderAction.Buy));
 }
Пример #10
0
        public void ComparesAgainstExternalDataOnStochasticsD()
        {
            var stochastics = new Stochastic("sto", 12, 3, 5);

            const double epsilon = 1e-3;

            TestHelper.TestIndicator(stochastics, "spy_with_stoch12k3.txt", "%D 5",
                                     (ind, expected) => Assert.AreEqual(expected, (double)((Stochastic)ind).StochD.Current.Value, epsilon)
                                     );
        }
Пример #11
0
        public void D_Single_SimpleValues_Calculated()
        {
            //Given
            double[] data = { 1, 2, 3, 4, 5, 6, 5, 8, 4, 7 };

            //When
            var result = Stochastic.D_Single(data, period: 5, k_period: 3);

            //Then
            Assert.Equal(88.89D, Math.Round(result.Value, 2));
        }
Пример #12
0
        public void K_Single_SimpleValues_Calculated()
        {
            //Given
            double[] data = { 1, 2, 3, 4, 5, 6, 5, 8, 4, 7 };

            //When
            var result = Stochastic.K_Single(data, period: 5);

            //Then
            Assert.Equal(75D, result);
        }
Пример #13
0
        public void D_Single_DataLengthLessThanPeriod_ReturnZero()
        {
            //Given
            double[] data = { 1, 2, 3, 4, 5, 6, 5, 8, 4, 7 };

            //When
            var result = Stochastic.D_Single(data, period: 11);

            //Then
            Assert.Equal(0, result);
        }
Пример #14
0
        public void D_simplevalues_calculated()
        {
            //Given
            double[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            //When
            double?[] result   = Stochastic.D(data, period: 5, k_period: 3);
            double?[] expected = { null, null, null, null, 100, 100, 100, 100, 100, 100 };
            //Then
            Assert.Equal(expected, result);
        }
Пример #15
0
    private void BuildTexure(List <Vector2> samples)
    {
        if (texturePixels == null || texturePixels.Length != IMAGE_LENGTH * IMAGE_LENGTH || lights == null || sampleWeights == null || sampleWeights.Length != IMAGE_LENGTH * IMAGE_LENGTH)
        {
            Initialize();
        }

        Vector2 center = new Vector2(.5f, .5f);

        int samplesAAexp = aaQuality;

        float pixelLength = 1f / IMAGE_LENGTH;

        foreach (Vector2 sample in samples)
        {
            int x = Mathf.Clamp((int)(sample.x * IMAGE_LENGTH), 0, IMAGE_LENGTH - 1);
            int y = Mathf.Clamp((int)(sample.y * IMAGE_LENGTH), 0, IMAGE_LENGTH - 1);;

            List <Vector2> aaSamples = Stochastic.GetStratifiedUniformGrid(samplesAAexp, samplesAAexp);
            Color          pixel     = Color.black;

            foreach (Vector2 aa in aaSamples)
            {
                Vector2 p = sample + aa * pixelLength;

                if ((p - center).magnitude < .5f)
                {
                    pixel += RenderPixel((p - center) / .5f) / aaSamples.Count;
                }
                else
                {
                    // Background pixel
                    Vector2 dirToPoint = p - center;
                    Vector2 edge       = dirToPoint.normalized;
                    //pixel += RenderPixel(edge *.999f) / aaSamples.Count;
                }
            }

            Color previousColor  = texturePixels[y * IMAGE_LENGTH + x];
            float previousWeight = sampleWeights[y * IMAGE_LENGTH + x];

            sampleWeights[y * IMAGE_LENGTH + x] += 1f;

            if (previousWeight > 0.0001f)
            {
                texturePixels[y * IMAGE_LENGTH + x] = ((previousColor * previousWeight) + pixel) / (previousWeight + 1f);
            }
            else
            {
                texturePixels[y * IMAGE_LENGTH + x] = pixel;
            }
        }
    }
Пример #16
0
        public void HandlesEqualMinAndMax()
        {
            var reference   = DateTime.Now;
            var stochastics = new Stochastic("sto", 2, 2, 2);

            for (var i = 0; i < 4; i++)
            {
                var bar = new TradeBar(reference.AddSeconds(i), Symbols.SPY, 1, 1, 1, 1, 1);
                stochastics.Update(bar);
                Assert.AreEqual(0m, stochastics.Current.Value);
            }
        }
Пример #17
0
        protected override string GetPresentDetail(IOutputInstant Instant, IIndicatorValues Data, IndicatorParameters IndicatorParameters)
        {
            Stochastic stochastic = Data.SlowStochastic(IndicatorParameters)[Instant.ExposureDate];

            if (stochastic != null)
            {
                return(String.Format("{0}|{1}|{2}|{3}|", stochastic.PercentageK, stochastic.PercentageD, (int)stochastic.Oscillation, stochastic.Oscillation));
            }
            else
            {
                return(String.Format("{0}|{1}|{2}|{3}|", "", "", "", ""));
            }
        }
Пример #18
0
        public SuperSmoothedDoubleStochastic(string name, int period, int kPeriod, int dPeriod)
            : base(name)
        {
            _maximum        = new Maximum(name + "_Max", period);
            _mininum        = new Minimum(name + "_Min", period);
            _stochastic     = new Stochastic(name + "_Stoch", period, kPeriod, dPeriod);
            _firstSmoothing = new SimpleMovingAverage(3);

            Smoothed = new FunctionalIndicator <TradeBar>(name + "_Smoothed",
                                                          input => ComputeSmoothed(period, input),
                                                          smoothed => _maximum.IsReady,
                                                          () => _maximum.Reset()
                                                          );
        }
Пример #19
0
        public void HandlesEqualMinAndMax()
        {
            var reference   = new DateTime(2015, 09, 01);
            var stochastics = new Stochastic("sto", 2, 2, 2);

            for (int i = 0; i < 4; i++)
            {
                var bar = new TradeBar {
                    Time = reference.AddSeconds(i)
                };
                bar.Open = bar.Close = bar.High = bar.Low = bar.Volume = 1;
                stochastics.Update(bar);
                Assert.AreEqual(0m, stochastics.Current.Value);
            }
        }
        public void Run(string downloadTime)
        {
            DateTime           date          = DateTime.Now;
            DownloadEngine     download      = new DownloadEngine();
            Formatting         formatting    = new Formatting();
            PeregrineOperation peregrine     = new PeregrineOperation();
            MACD                macd         = new MACD();
            Stochastic          stochastic   = new Stochastic();
            TechnicalIndicators indicators   = new TechnicalIndicators();
            Transactions        transactions = new Transactions();
            WebClient           web          = new WebClient(); // provides the ability to download from the internet
            WebURIs             uRIs         = new WebURIs();   // refers to an instance of the Wall Street Journal URL

            DownloadTimer(download, formatting, peregrine, macd, stochastic, indicators, transactions, web, uRIs, Database, downloadTime);
        }
Пример #21
0
    public void Update()
    {
        if (previewMode)
        {
            int previewSamples = (int)(IMAGE_LENGTH);

            BuildTexure(Stochastic.GetStratifiedUniformGrid(previewSamples, previewSamples));

            updateCounter++;

            if (updateCounter > 1)
            {
                sphereMap.SetPixels(texturePixels);
                sphereMap.Apply();
                updateCounter = 0;
            }
        }
    }
 protected override void Create()
 {
     m_stochastic1 = new Stochastic(this);
     m_ofastk      = new VariableSeries <Double>(this);
     m_ofastd      = new VariableSeries <Double>(this);
     m_oslowk      = new VariableSeries <Double>(this);
     m_oslowd      = new VariableSeries <Double>(this);
     Plot1         =
         AddPlot(new PlotAttributes("SlowK", 0, Color.Yellow,
                                    Color.Empty, 0, 0, true));
     Plot2 =
         AddPlot(new PlotAttributes("SlowD", 0, Color.Blue,
                                    Color.Empty, 0, 0, true));
     Plot3 =
         AddPlot(new PlotAttributes("OverBot", 0, Color.Green,
                                    Color.Empty, 0, 0, true));
     Plot4 =
         AddPlot(new PlotAttributes("OverSld", 0, Color.Green,
                                    Color.Empty, 0, 0, true));
 }
Пример #23
0
        public void ResetsProperly()
        {
            var stochastics = new Stochastic("sto", 12, 3, 5);

            foreach (var bar in TestHelper.GetTradeBarStream("spy_with_stoch12k3.txt", false))
            {
                stochastics.Update(bar);
            }
            Assert.IsTrue(stochastics.IsReady);
            Assert.IsTrue(stochastics.FastStoch.IsReady);
            Assert.IsTrue(stochastics.StochK.IsReady);
            Assert.IsTrue(stochastics.StochD.IsReady);

            stochastics.Reset();

            TestHelper.AssertIndicatorIsInDefaultState(stochastics);
            TestHelper.AssertIndicatorIsInDefaultState(stochastics.FastStoch);
            TestHelper.AssertIndicatorIsInDefaultState(stochastics.StochK);
            TestHelper.AssertIndicatorIsInDefaultState(stochastics.StochD);
        }
Пример #24
0
        /// <summary>
        /// Rolls a start and end point--wrapping allowed--and scrambles the elements between.
        /// </summary>
        /// <typeparam name="T">The array data type.</typeparam>
        /// <param name="arry"></param>
        /// <returns>The scrambled array.</returns>
        protected T[] Scramble <T>(T[] arry)
        {
            var N       = arry.Count();
            var newArry = new T[N];

            Array.Copy(arry, newArry, N);

            var start = Stochastic.Next(N);
            var end   = Stochastic.Next(N);

            while (end != start)
            {
                end = Stochastic.Next(N);
            }

            var isWrapped = start > end;
            var offset    = isWrapped ? end + 1 : 0;

            //If isWrapped (N-start) count back end & (start+1) counts front end.
            var len       = end - start + 1 + (isWrapped ? N : 0);
            var scrambled = new T[len];

            for (var i = 0; i < len; i++)
            {
                scrambled[i] = arry[(start + i) % N];
            }

            scrambled = Stochastic.Shuffle(scrambled);

            for (var i = 0; i < len; i++)
            {
                newArry[(start + i) % N] = scrambled[i];
            }

            return(newArry);
        }
        public StochasticSeries(C1FlexChart chart, string plotAreaName) : base()
        {
            Chart = chart;
            Chart.BeginUpdate();

            AxisY.TitleStyle            = new ChartStyle();
            AxisY.TitleStyle.FontWeight = Windows.UI.Text.FontWeights.Bold;
            AxisY.Position       = C1.Chart.Position.Right;
            AxisY.PlotAreaName   = plotAreaName;
            AxisY.Title          = "Stoc";
            AxisY.Labels         = false;
            AxisY.MajorTickMarks = AxisY.MinorTickMarks = C1.Chart.TickMark.None;

            series            = new Stochastic();
            series.DLineStyle = new ChartStyle();
            series.DLineStyle.StrokeThickness = 1;
            series.KLineStyle = new ChartStyle();
            series.KLineStyle.StrokeThickness = 1;
            series.ChartType             = C1.Chart.Finance.FinancialChartType.Line;
            series.Style                 = new ChartStyle();
            series.Style.Stroke          = new SolidColorBrush(Color.FromArgb(255, 51, 103, 214));
            series.Style.Fill            = new SolidColorBrush(Color.FromArgb(128, 66, 133, 244));
            series.Style.StrokeThickness = 1;
            series.BindingX              = "Date";
            series.Binding               = "High,Low,Close";

            series.AxisY = AxisY;
            Chart.Series.Add(series);

            ThresholdSeries overBought = new ThresholdSeries();

            overBought.ChartType             = C1.Chart.Finance.FinancialChartType.Line;
            overBought.Style                 = new ChartStyle();
            overBought.Style.Stroke          = new SolidColorBrush(ViewModel.IndicatorPalettes.StockGreen);
            overBought.Style.StrokeThickness = 1;

            overBought.AxisY = AxisY;
            Chart.Series.Add(overBought);

            ThresholdSeries overSold = new ThresholdSeries();

            overSold.ChartType             = C1.Chart.Finance.FinancialChartType.Line;
            overSold.Style                 = new ChartStyle();
            overSold.Style.Stroke          = new SolidColorBrush(ViewModel.IndicatorPalettes.StockRed);
            overSold.Style.StrokeThickness = 1;

            overSold.AxisY = AxisY;
            Chart.Series.Add(overSold);

            Utilities.Helper.BindingSettingsParams(chart, this, typeof(StochasticSeries), "Stochastic",
                                                   new Data.PropertyParam[]
            {
                new Data.PropertyParam("StochasticType", typeof(StochasticPresetType)),
            },
                                                   () =>
            {
                this.OnSettingParamsChanged();
            }
                                                   );

            Utilities.Helper.BindingSettingsParams(chart, series, typeof(Stochastic), "Stochastic",
                                                   new Data.PropertyParam[]
            {
                new Data.PropertyParam("KPeriod", typeof(int)),
                new Data.PropertyParam("DPeriod", typeof(int)),
                new Data.PropertyParam("SmoothingPeriod", typeof(int)),
                new Data.PropertyParam("DLineStyle.Stroke", typeof(Brush)),
                new Data.PropertyParam("KLineStyle.Stroke", typeof(Brush))
            },
                                                   () =>
            {
                this.OnSettingParamsChanged();
            }
                                                   );

            Utilities.Helper.BindingSettingsParams(chart, overBought, typeof(ThresholdSeries), "Stochastic",
                                                   new Data.PropertyParam[]
            {
                new Data.PropertyParam("ZonesVisibility", typeof(bool)),
                new Data.PropertyParam("Threshold", typeof(int), "OverBought"),
            },
                                                   () =>
            {
                this.OnSettingParamsChanged();
            }
                                                   );
            Utilities.Helper.BindingSettingsParams(chart, overSold, typeof(ThresholdSeries), "Stochastic",
                                                   new Data.PropertyParam[]
            {
                new Data.PropertyParam("ZonesVisibility", typeof(bool)),
                new Data.PropertyParam("Threshold", typeof(int), "OverSold"),
            },
                                                   () =>
            {
                this.OnSettingParamsChanged();
            }
                                                   );
            overBought.OnThesholdChanged += (o, e) =>
            {
                this.OnSettingParamsChanged();
            };
            overSold.OnThesholdChanged += (o, e) =>
            {
                this.OnSettingParamsChanged();
            };

            //binding series color to axis title.
            Binding binding = new Binding();

            binding.Path   = new Windows.UI.Xaml.PropertyPath("Stroke");
            binding.Source = series.Style;
            BindingOperations.SetBinding(AxisY.TitleStyle, ChartStyle.StrokeProperty, binding);

            Chart.EndUpdate();

            this.Series = new FinancialSeries[] { series, overBought, overSold };
        }
        /// Prediction Algo via Technical Indicators
        public List <Results> MathPredictsTheFuture(DownloadEngine download, MACD macd, Stochastic stochastic,
                                                    Transactions transactions, TechnicalIndicators indicators, string stock)
        {
            DateTime date = transactions.DatabaseDateQuery(database, stock)[0];
            // 50 Day Average - queries database and calculates the 50 day average
            double FiftyDayAverage = indicators.FiftyDayAvg(stock, transactions);

            // MACD - determines if a stock is bearish or bullish. Uses 12 and 26 period exponental moving average
            List <MACD> todaysMACD = macd.TodaysMACD(stock, transactions);
            // Stochastic
            List <Stochastic> todayStoch = stochastic.StochasticToday(Database, stock);

            List <Results> results = new List <Results>()
            {
                new Results
                {
                    Date             = date,
                    CIK              = download.DatabaseCIKQuery(Database, stock),
                    Symbol           = stock,
                    LastClose        = transactions.CloseQuery(Database, stock),
                    FiftyDayAvg      = FiftyDayAverage,
                    mACD             = todaysMACD[0].MACDValue,
                    MACDSignal       = todaysMACD[0].MACDSignal,
                    EMA12            = todaysMACD[0].EMA12,
                    EMA26            = todaysMACD[0].EMA26,
                    StochasticFast   = todayStoch[0].Fast,
                    StochasticSlow   = todayStoch[0].Slow,
                    StochasticSignal = todayStoch[0].Signal
                }
            };

            return(results);
        }
Пример #27
0
        public SVMBaselineSignalWIP(
            QuoteBarConsolidator consolidator,
            Stochastic stoch,
            ExponentialMovingAverage stochMA,
            RollingWindow <IndicatorDataPoint> rollingStochMA,
            LeastSquaresMovingAverage stochEmaLSMA,
            RollingWindow <IndicatorDataPoint> rollingStochEmaSlope,
            ExponentialMovingAverage ema,
            LeastSquaresMovingAverage emaMA,
            RollingWindow <IndicatorDataPoint> rollingEmaSlope,
            ExponentialMovingAverage shortTermMA,
            LeastSquaresMovingAverage dailyEmaLSMA,
            RollingWindow <IndicatorDataPoint> rollingDailyEmaSlope,
            SecurityHolding securityHolding,
            Security security,
            SVMBaselineStrategyWIP qcAlgorithm)
        {
            _consolidator         = consolidator;
            _stoch                = stoch;
            _stochMA              = stochMA;
            _rollingStochMA       = rollingStochMA;
            _stochEmaLSMA         = stochEmaLSMA;
            _rollingStochEmaSlope = rollingStochEmaSlope;
            _ema                  = ema;
            _emaMA                = emaMA;
            _rollingEmaSlope      = rollingEmaSlope;
            _shortTermMA          = shortTermMA;
            _dailyEmaLSMA         = dailyEmaLSMA;
            _rollingDailyEmaSlope = rollingDailyEmaSlope;

            _securityHolding       = securityHolding;
            _security              = security;
            _minimumPriceVariation = (1m / _security.SymbolProperties.MinimumPriceVariation) / 10m;
            _qcAlgorithm           = qcAlgorithm;

            _stochMA.Updated += (sender, args) =>
            {
                try
                {
                    var currentQuote = (QuoteBar)_consolidator.Consolidated;

                    var aboveEma = currentQuote.Close - _ema.Current.Value > 4m / _minimumPriceVariation;
                    var belowEma = _ema.Current.Value - currentQuote.Close > 4m / _minimumPriceVariation;

                    var aboveEmaExit = (currentQuote.Close - _ema.Current.Value > 10m / _minimumPriceVariation) || _rollingDailyEmaSlope[0] > 0.0005m;
                    var belowEmaExit = (_ema.Current.Value - currentQuote.Close > 10m / _minimumPriceVariation) || _rollingDailyEmaSlope[0] < -0.0005m;

                    var longCondition = _rollingStochMA[0] > _rollingStochMA[1] &&
                                        _stochMA > 55 &&
                                        aboveEma &&
                                        //_rollingDailyEmaSlope[0] > _rollingDailyEmaSlope[1] &&
                                        _dailyEmaLSMA.Slope > 0 &&
                                        //_rollingStochEmaSlope[0] < 2 &&
                                        //_rollingStochEmaSlope[0] > _rollingStochEmaSlope[1] &&
                                        //_rollingStochMA[0] > 45 &&
                                        _rollingEmaSlope[0] > 0.00001m;
                    var shortCondition = _rollingStochMA[0] < _rollingStochMA[1] &&
                                         _stochMA < 45 &&
                                         belowEma &&
                                         //_rollingDailyEmaSlope[0] < _rollingDailyEmaSlope[1] &&
                                         _dailyEmaLSMA.Slope < 0 &&
                                         //_rollingStochEmaSlope[0] > -2 &&
                                         //_rollingStochEmaSlope[0] < _rollingStochEmaSlope[1] &&
                                         //_rollingStochMA[0] < 55 &&
                                         _rollingEmaSlope[0] < -0.00001m;

                    var prediction = longCondition ? 1 : shortCondition ? -1 : 0;

                    /*var prediction = _rollingStochMA[0] > _rollingStochMA[1] && aboveEma && _stochEmaLSMA.Slope > 0.5 && _rollingEmaSlope[0] > 0
                     *  ? 1
                     *  : _rollingStochMA[0] < _rollingStochMA[1] && belowEma && _stochEmaLSMA.Slope < -0.5 && _rollingEmaSlope[0] < 0
                     *      ? -1
                     *      : 0;*/
                    var probability   = 1d;
                    var logLikelihood = 1d;

                    _qcAlgorithm.PlotSignal((QuoteBar)_consolidator.Consolidated, prediction, logLikelihood);

                    var longExit  = Signal == SignalType.Long && belowEmaExit && _rollingEmaSlope[0] < 0;
                    var shortExit = Signal == SignalType.Short && aboveEmaExit && _rollingEmaSlope[0] > 0;

                    /*var longExit = Signal == SignalType.Long && _stochEmaLSMA.Slope < -0.5;
                     * var shortExit = Signal == SignalType.Short && _stochEmaLSMA.Slope > 0.5;*/

                    if (!_securityHolding.Invested && prediction == 1)
                    {
                        if (true)//if (!_shortOnly.Contains(_securityHolding.Symbol))
                        {
                            Signal = Signal != SignalType.PendingLong ? SignalType.Long : SignalType.Long;
                        }
                        else
                        {
                            Signal = SignalType.NoSignal;
                        }
                        //Signal = Signal != SignalType.PendingLong ? SignalType.Long : SignalType.Long;
                        //Signal = SignalType.NoSignal;

                        if (_debug)
                        {
                            Console.WriteLine("Long Signal: {0} Probability: {1} Log Likelihood: {2}", Signal, probability, logLikelihood);
                            Console.WriteLine("Long STO: {0} STO MA: {1}", _stoch.Current.Value, args.Value);
                            Console.WriteLine("Long Time: {0} Price: {1}", _consolidator.Consolidated.Time, _consolidator.Consolidated.Value);
                        }
                    }
                    else if (!_securityHolding.Invested && prediction == -1)
                    {
                        if (true) //if (_shortable.Contains(_securityHolding.Symbol))
                        {
                            Signal = Signal != SignalType.PendingShort ? SignalType.Short : SignalType.Short;
                        }
                        else
                        {
                            Signal = SignalType.NoSignal;
                        }
                        //Signal = Signal != SignalType.PendingShort ? SignalType.Short : SignalType.Short;
                        //Signal = SignalType.NoSignal;

                        if (_debug)
                        {
                            Console.WriteLine("Short Signal: {0} Probability: {1} Log Likelihood: {2}", Signal, probability, logLikelihood);
                            Console.WriteLine("Short STO: {0} STO MA: {1}", _stoch.Current.Value, args.Value);
                            Console.WriteLine("Short Time: {0} Price: {1}", _consolidator.Consolidated.Time, _consolidator.Consolidated.Value);
                        }
                    }
                    else if ((_securityHolding.Invested && longExit) || (_securityHolding.Invested && shortExit))
                    {
                        if (_debug)
                        {
                            Console.WriteLine("Exit Signal: {0} Probability: {1} Log Likelihood: {2}", Signal, probability, logLikelihood);
                            Console.WriteLine("Exit STO: {0} STO MA: {1}", _stoch.Current.Value, args.Value);
                            Console.WriteLine("Exit Time: {0} Price: {1}", _consolidator.Consolidated.Time, _consolidator.Consolidated.Value);
                        }

                        Signal = SignalType.Exit;
                    }
                    else if (!_securityHolding.Invested && (Signal == SignalType.PendingLong || Signal == SignalType.PendingShort))
                    {
                        Signal = SignalType.NoSignal;
                    }
                    else
                    {
                        //Signal = SignalType.NoSignal;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Signal = SignalType.NoSignal;
                }
            };
        }
Пример #28
0
        /// <inheritdoc />
        public void Iteration()
        {
            _network.NetworkTraining = true;

            // alert the layers that a new batch is starting.
            foreach (var layer in _network.Layers)
            {
                layer.TrainingBatch(Stochastic);
            }

            // begin the iteration
            _gradients.Reset();
            _errorCalc.Clear();

            var iterationSize = BatchSize == 0
                ? _training.Count
                : Math.Min(BatchSize, _training.Count);


            for (var i = 0; i < iterationSize; i++)
            {
                BasicData element;

                if (IsOnlineTraining)
                {
                    if (Stochastic != null)
                    {
                        var stochasticIndex = Stochastic.NextInt(0, _training.Count);
                        element = _training[stochasticIndex];
                    }
                    else
                    {
                        element = _training[_currentIndex++];
                    }
                }
                else
                {
                    element = _training[i];
                }
                _gradients.Process(_errorCalc, element.Input, element.Ideal);
            }

            if (_currentIndex > _training.Count || BatchSize == 0)
            {
                _currentIndex = 0;
            }

            _currentError = _errorCalc.Calculate();

            for (var i = 0; i < _network.Weights.Length; i++)
            {
                double delta;

                if (NesterovUpdate)
                {
                    var prevNesterov = _lastDelta[i];

                    _lastDelta[i] = Momentum * prevNesterov
                                    + _gradients.Gradients[i] * LearningRate;
                    delta = Momentum * prevNesterov - (1 + Momentum) * _lastDelta[i];
                }
                else
                {
                    delta         = _gradients.Gradients[i] * -LearningRate + _lastDelta[i] * Momentum;
                    _lastDelta[i] = delta;
                }

                _network.Weights[i] += delta;
            }
            _network.NetworkTraining = false;
        }
        private void DownloadTimer(DownloadEngine download, Formatting formatting, PeregrineOperation peregrine, MACD macd, Stochastic stochastic,
                                   TechnicalIndicators indicators, Transactions transactions, WebClient web, WebURIs uRIs, string Database, string downloadTime)
        {
            var DailyTime = downloadTime;  //Time when method needs to be called

            var timeParts = DailyTime.Split(new char[1] {
                ':'
            });

            var dateNow = DateTime.Now;
            var date    = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day,
                                       int.Parse(timeParts[0]), int.Parse(timeParts[1]), int.Parse(timeParts[2]));
            TimeSpan ts;

            if (date > dateNow)
            {
                ts = date - dateNow;
            }
            else
            {
                date = date.AddDays(1);
                ts   = date - dateNow;
            }
            while (date != dateNow)
            {
                Console.WriteLine($"Waiting for {downloadTime}");
                //waits certan time and run the code
                Task.Delay(ts).ContinueWith((x) => Download(date, download, formatting, peregrine, macd, stochastic, indicators, transactions, web, uRIs, Database));
                Console.Read();
            }
        }
        /// Download and save to Database
        private void Download(DateTime date, DownloadEngine download, Formatting formatting, PeregrineOperation peregrine, MACD macd, Stochastic stochastic, TechnicalIndicators indicators, Transactions transactions, WebClient web, WebURIs uRIs, string Database)
        {
            List <string> Symbols = transactions.DatabaseSymbolListQuery(Database, stocks);

            transactions.TruncateStockTable(Database, "Clean Data"); // clears data from the clean data table.
            int count = 1;

            foreach (var stock in Symbols)
            {
                Console.Clear();
                Console.WriteLine($"Downloading {stock} || {count} of {Symbols.Count}");
                download.ToDatabase(date, formatting, peregrine, transactions, web, uRIs, stock, Database);
                count++;
            }
            Console.WriteLine("I'm Done");
            //count = 1;
            //calls the list of stocks that have been data verified
            //List<string> CleanData = transactions.DatabaseSymbolListQuery(Database, stocks);
            //foreach (var stock in CleanData)
            //{
            //    Console.Clear();
            //    Console.WriteLine($"Doing Math {stock} || {count} of {CleanData.Count}");
            //    List<Results> results = MathPredictsTheFuture(download, macd, stochastic, transactions, indicators, stock);
            //    transactions.SaveToTableResult(Database, results); // saves the calculations to the Results table in the database
            //    count++;
            //}


            //// calls the stocks from the results list
            //List<PeregrineResults> todaysResults = transactions.DailyResultsQuery(peregrine.Database);
            //transactions.TruncateStockTable(database, peregrineresults); // clears the web results table. This table feeds the model for the ASP.Net interface.
            //transactions.SaveToTableWebResult(peregrine.Database, todaysResults);
            //Console.WriteLine("Peregrine Results Updated");
        }
 protected override void Create(){
     m_Stochastic = new Stochastic(this);
     m_oFastK = new VariableSeries<Double>(this);
     m_oFastD = new VariableSeries<Double>(this);
     m_oSlowK = new VariableSeries<Double>(this);
     m_oSlowD = new VariableSeries<Double>(this);
     m_StochLE =
         OrderCreator.MarketNextBar(new SOrderParameters(Contracts.Default, "StochLE", EOrderAction.Buy));
 }
 protected override void Create(){
     m_stochastic1 = new Stochastic(this);
     m_ofastk = new VariableSeries<Double>(this);
     m_ofastd = new VariableSeries<Double>(this);
     m_oslowk = new VariableObject<Double>(this);
     m_oslowd = new VariableObject<Double>(this);
     Plot1 =
         AddPlot(new PlotAttributes("FastK", 0, Color.Yellow,
                                    Color.Empty, 0, 0, true));
     Plot2 =
         AddPlot(new PlotAttributes("FastD", 0, Color.Blue,
                                    Color.Empty, 0, 0, true));
     Plot3 =
         AddPlot(new PlotAttributes("OverBot", 0, Color.Green,
                                    Color.Empty, 0, 0, true));
     Plot4 =
         AddPlot(new PlotAttributes("OverSld", 0, Color.Green,
                                    Color.Empty, 0, 0, true));
 }