public void ReturnsDateOfMostRecentEntry()
            {
                //// SETUP

                // Test Data
                var stock = new Stock { Ticker = "FLWS", CompanyName = "1-800 FLOWERS.COM" };
                var oldest = new HistoricPrice { Stock = stock, Date = DateTime.Parse("1/1/2000") };
                var middle = new HistoricPrice { Stock = stock, Date = DateTime.Parse("1/2/2000") };
                var newest = new HistoricPrice { Stock = stock, Date = DateTime.Parse("1/3/2000") };
                var testData = new List<HistoricPrice> { oldest, newest, middle };

                // Create a mock generic repository.
                var mockGenericRepository = new Mock<IReadOnlyRepository<HistoricPrice>>();
                mockGenericRepository.Setup(mock => mock.FilterBy(It.IsAny<Expression<Func<HistoricPrice, bool>>>())).Returns(testData.AsQueryable());

                // Setup target
                var target = new ReadOnlyPriceHistoryRepository(mockGenericRepository.Object);

                // EXECUTE
                var actual = target.GetMostRecentDateForTicker(stock.Ticker);

                // VERIFY
                Assert.AreEqual(newest.Date, actual);
                mockGenericRepository.Verify(mock => mock.FilterBy(It.IsAny<Expression<Func<HistoricPrice, bool>>>()), Times.Once());
            }
        private void ComputeVolatility(HistoricPrice historicPrice, out double volatility, out double inverseVolatility)
        {
            var candles = historicPrice.Candles.OrderBy(r => r.Datetime);
            // Taking trouble to use last one month calendar days!
            var oneMonthAgo     = DateTime.Now.AddMonths(-1).AddDays(-1);
            var oneMonthRecords = candles
                                  .Where(r => r.Datetime >= new DateTimeOffset(oneMonthAgo)
                                         .ToUnixTimeSeconds()).Select(r => (double)r.Close);

            volatility        = Compute.ComputeMomentum.CalculateRsi(oneMonthRecords);
            volatility        = Math.Sqrt(oneMonthRecords.Average(z => z * z) - Math.Pow(oneMonthRecords.Average(), 2));
            inverseVolatility = 1.0 / volatility;
        }
        private void ComputeMomentum(HistoricPrice historicPrice, out double momentum, out double volatility)
        {
            var closingPrices       = historicPrice.Candles.Select(r => Math.Log((double)r.Close)).ToArray();
            var seqNumbers          = Enumerable.Range(0, closingPrices.Count()).Select <int, double>(i => i).ToArray();
            var leastSquaresFitting = Fit.Line(seqNumbers, closingPrices);
            var correlationCoff     = GoodnessOfFit.R(seqNumbers, closingPrices);
            var annualizedSlope     = (Math.Pow(Math.Exp(leastSquaresFitting.Item2), 252) - 1) * 100;
            var score = annualizedSlope * correlationCoff * correlationCoff;

            momentum = score;
            var r = Math.Exp(leastSquaresFitting.Item2) * correlationCoff * correlationCoff * 100;

            volatility = r;
        }
Exemple #4
0
        public static double ComputeMomentumValue(HistoricPrice historicPrice)
        {
            var logPrices = historicPrice.Candles.Select(r => Math.Log((double)r.Close));
            var count     = logPrices.Count();
            var xAxis     = new List <double>();

            for (int i = 1; i <= count; i++)
            {
                xAxis.Add(i);
            }
            LinearRegression(xAxis, logPrices, out double rSquared, out double yIntercept, out double slope);
            //Annualized percent
            var annualizedSlope = (Math.Pow(Math.Exp(slope), logPrices.Count()) - 1) * 100;
            //Adjust for fitness
            var score = annualizedSlope * rSquared;

            return(score);
        }
        private async Task <SecurityAnalysis> ComputeValuesAsync(HistoricPrice hp)
        {
            SecurityAnalysis sa = new SecurityAnalysis
            {
                Symbol = hp.Symbol
            };

            //await Task.FromResult(TestFunc(2));
            sa.DollarVolumeAverage = await Task.FromResult(ComputeDollarVolume(hp));

            sa.EfficiencyRatio = await Task.FromResult(ComputeEfficiencyRatio(hp));

            ComputeMomentum(hp, out double momentum, out double volatility);
            sa.Momentum = momentum;
            ComputeVolatility(hp, out volatility, out double inverseVolatility);
            sa.ThirtyDayVolatility = volatility;
            sa.VolatilityInverse   = inverseVolatility;
            //sa.PietroskiFScore = await ComputePietroskiScore(hp.Symbol);
            return(sa);
        }
        private double ComputeEfficiencyRatio(HistoricPrice hp)
        {
            // We are computing efficiency ratio based on prices for the last one month.
            // Taking trouble to use last one month calendar days!
            var candles         = hp.Candles.OrderBy(r => r.Datetime);
            var oneMonthAgo     = DateTime.Now.AddMonths(-1).AddDays(-1);
            var oneMonthAgoSecs = new DateTimeOffset(oneMonthAgo).ToUnixTimeSeconds();
            var recordsToCount  = candles.Where(r => r.Datetime >= oneMonthAgoSecs).Count();
            var recordsToUse    =
                (from candle in candles
                 select new Trady.Core.Candle(
                     dateTime: DateTimeOffset.FromUnixTimeSeconds(candle.Datetime),
                     open: candle.Open,
                     high: candle.High,
                     low: candle.Low,
                     close: candle.Close,
                     candle.Volume)).OrderBy(r => r.DateTime).ToList();
            var efficiencyRatio = Convert.ToDouble(recordsToUse.Er(recordsToCount).Last().Tick ?? 0) * 100.0;

            return(efficiencyRatio);
        }
 private double ComputeDollarVolume(HistoricPrice hp)
 {
     try
     {
         var computeCandles = (from candle in hp.Candles
                               select new Trady.Core.Candle(
                                   dateTime: DateTimeOffset.FromUnixTimeSeconds(candle.Datetime),
                                   open: candle.Open * candle.Volume,
                                   high: candle.High * candle.Volume,
                                   low: candle.Low * candle.Volume,
                                   close: candle.Close * candle.Volume,
                                   candle.Volume)).OrderBy(r => r.DateTime);
         var a = computeCandles.FirstOrDefault();
         return(Convert.ToDouble(computeCandles.Ema(30).Last().Tick ?? 0.0M));
     }
     catch (Exception ex)
     {
         logger.LogError($"Computing Dollar Volume for {hp.Symbol}");
         logger.LogError($"Error while importing historic data for momentum compute; reason\n\t{ex.Message}");
         return(0);
     }
 }
            public void AddsHistoricPriceWhenPriceIsNew()
            {
                //// SETUP

                // Test Data
                var price1 = new HistoricPrice { Date = DateTime.Parse("1/1/2000") };
                var price2 = new HistoricPrice { Date = DateTime.Parse("1/2/2000") };
                var price3 = new HistoricPrice { Date = DateTime.Parse("1/3/2000") };

                // Setup target
                var target = new Stock { Ticker = "FLWS", CompanyName = "1-800 FLOWERS.COM" };

                // EXECUTE (3 times)
                var actual1 = target.AddHistoricPrice(price1);
                var actual2 = target.AddHistoricPrice(price2);
                var actual3 = target.AddHistoricPrice(price3);

                //// VERIFY

                Assert.AreEqual(3, target.PriceHistory.Count);

                // Price 1
                Assert.True(actual1);
                Assert.True(target.PriceHistory.Contains(price1));
                Assert.AreSame(target, price1.Stock);

                // Price 2
                Assert.True(actual2);
                Assert.True(target.PriceHistory.Contains(price2));
                Assert.AreSame(target, price2.Stock);

                // Price 3
                Assert.True(actual3);
                Assert.True(target.PriceHistory.Contains(price3));
                Assert.AreSame(target, price2.Stock);
            }
            public void DoesNotAddHistoricPriceWhenPriceIsPreexisting()
            {
                //// SETUP

                // Test Data
                var price = new HistoricPrice { Date = DateTime.Parse("1/1/2000") };
                var duplicatePrice = new HistoricPrice { Date = DateTime.Parse("1/1/2000") };

                // Setup target
                var target = new Stock { Ticker = "FLWS", CompanyName = "1-800 FLOWERS.COM" };

                // EXECUTE (twice)
                var initialActual = target.AddHistoricPrice(price);
                var duplicateActual = target.AddHistoricPrice(duplicatePrice);

                //// VERIFY

                Assert.AreEqual(1, target.PriceHistory.Count);

                // Initial (Should have succeeded)
                Assert.True(initialActual);
                Assert.True(target.PriceHistory.Contains(price));
                Assert.AreSame(target, price.Stock);

                // Duplicate (Should have failed)
                Assert.False(duplicateActual);
                Assert.Null(duplicatePrice.Stock);
            }