예제 #1
0
        public async Task <string> SelectRandomGoodFirms()
        {
            _logger.LogInformation("Starting to select firms for the requester");
            List <PiotroskiScoreMd> selectedFirms;

            try
            {
                selectedFirms = _connectionHandlerCF.Get(r => r.Rating >= 7 && r.FYear == DateTime.Now.Year)
                                .ToList();
                if (selectedFirms == null || !selectedFirms.Any())
                {
                    selectedFirms = _connectionHandlerCF.Get(r => r.Rating >= 7 && r.FYear == DateTime.Now.Year - 1)
                                    .ToList();
                }
                if (!selectedFirms.Any())
                {
                    return("");
                }
            }
            catch (Exception ex)
            {
                _logger.LogCritical("Error while getting data from MongoDb from Collection PiotroskiScore");
                _logger.LogCritical(ex.Message);
                return("");
            }
            selectedFirms.Shuffle();
            selectedFirms = selectedFirms.Take(4)
                            .OrderByDescending(r => r.Rating)
                            .ThenByDescending(r => r.Revenue)
                            .ToList();
            var messageString = new StringBuilder();

            messageString.Append("Here are a few recommendations for you.\n");
            foreach (var selectedFirm in selectedFirms)
            {
                var companyName = await _resolveCompanyName.ResolveTicker(selectedFirm.Ticker);

                var symbol = Regex.Replace(selectedFirm.Ticker, ".{1}", "$0 ");
                messageString.Append($"{companyName} with ticker {symbol} has Piotrosk-F Score of {selectedFirm.Rating}\n");
                QuotesFromWorldTrading quotes = await _obtainStockQuote.GetStockQuotes(selectedFirm.Ticker);

                var companyStats = await ObtainCompanyStats(selectedFirm.Ticker);

                if (quotes != null && quotes.Data.Any())
                {
                    var currentPrice = (float)quotes.Data[0].Price;
                    messageString.Append($"It last traded at ${Math.Round(currentPrice,2)}. ");
                }
                if (companyStats != null && companyStats.week52high != 0)
                {
                    var week52Low  = Math.Round(companyStats.week52low, 2);
                    var week52High = Math.Round(companyStats.week52high, 2);
                    var peRatio    = companyStats.peRatio == null ? 0 : companyStats.peRatio;
                    messageString.Append($"52 week range is between ${week52Low} and {week52High} and P E Ratio is {peRatio}. ");
                }
                messageString.Append("\n\n");
            }
            return(messageString.ToString());
        }
예제 #2
0
        public async Task <WebhookResponse> SelectRandomGoodFirms()
        {
            _log.LogTrace("Started to select better investments");
            try
            {
                var betterScores = _ratingsConnectionHandler.Get(r => r.Rating >= 7 && r.FYear == DateTime.Now.Year).ToList();
                if (betterScores == null || betterScores.Count == 0)
                {
                    betterScores = _ratingsConnectionHandler.Get(r => r.Rating >= 7 && r.FYear == DateTime.Now.Year - 1).ToList();
                }
                if (betterScores.Any())
                {
                    betterScores.Shuffle();
                }
                betterScores = betterScores.Take(4).ToList();
                var messageString = new StringBuilder();
                messageString.Append("Here are a few recommendations for you.\n");
                foreach (var piotroskiScore in betterScores)
                {
                    var companyName = _dbconCompany.Get(r => r.SimId.Equals(piotroskiScore.SimId)).FirstOrDefault().Name;
                    if (!string.IsNullOrWhiteSpace(companyName))
                    {
                        string targetPrice;
                        if (betterScores.First() != piotroskiScore)
                        {
                            var a = await Task.Delay(100).ContinueWith(t => GetTargetPriceAsync(piotroskiScore.Ticker));

                            targetPrice = a.Result;
                        }
                        else
                        {
                            targetPrice = await GetTargetPriceAsync(piotroskiScore.Ticker);
                        }
                        messageString.Append($"{companyName} with ticker {piotroskiScore.Ticker} scores {piotroskiScore.Rating}.\n");
                        if (!targetPrice.IsNullOrWhiteSpace())
                        {
                            messageString.Append(targetPrice);
                        }
                    }
                }
                messageString.Append($"\n Note: Recommendations are based on SEC filings. Market conditions will affect the company's performance.\n");
                messageString.Append($"\n Further research needs to be done before you place your order.\n");
                var returnResponse = new WebhookResponse
                {
                    FulfillmentText = messageString.ToString()
                };
                return(returnResponse);
            }
            catch (Exception ex)
            {
                _log.LogCritical($"Error while getting data from database;\n{ex.Message}");
                return(new WebhookResponse());
            }
        }
예제 #3
0
        public async Task <List <CompanyDetail> > GetAllCompaniesAsync()
        {
            var tmpList = await _dlf.GetCompanyList();

            allCompanies = new List <CompanyDetailMd>();
            var dbCompanies = _dbconCompany.Get().ToList();

            if (dbCompanies.Count() < 100 || dbCompanies.Where(x => x.IndustryTemplate.IsNullOrWhiteSpace()).Count() < 20)
            {
                var deleteStatus = await _dbconCompany.RemoveAll();

                if (deleteStatus == false)
                {
                    return(null);
                }
            }
            dbCompanies = _dbconCompany.Get().ToList();
            if (tmpList == null)
            {
                return(Mapper.Map <List <CompanyDetailMd>, List <CompanyDetail> >(dbCompanies));
            }
            foreach (var company in tmpList)
            {
                var dbCompany = dbCompanies.Where(x => x.SimId == company.SimId).FirstOrDefault();
                if (dbCompany != null)
                {
                    dbCompany.Name   = company.Name;
                    dbCompany.Ticker = company.Ticker;
                    allCompanies.Add(dbCompany);
                }
                else
                {
                    allCompanies.Add(new CompanyDetailMd(company));
                }
            }
            var insertStatus = await _dbconCompany.UpdateMultiple(allCompanies);

            if (insertStatus)
            {
                var listOfAllCompanies = Mapper.Map <List <CompanyDetailMd>, List <CompanyDetail> >(allCompanies);
                return(listOfAllCompanies);
            }
            return(null);
        }
예제 #4
0
        /// <summary>
        /// Get statements from data provider and insert it to database.
        /// </summary>
        /// <param name="simId">The sim identifier.</param>
        /// <returns></returns>
        public async Task <bool> UpdateStatements(string simId)
        {
            if (simId.IsNullOrWhiteSpace())
            {
                return(false);
            }

            var cd = _hcl.GetCompanyDetails(simId);

            if (cd.LastUpdate != null && ((TimeSpan)(DateTime.Now - cd.LastUpdate)).Days < 30)
            {
                return(true);
            }

            var companyFinancials = await ObtainCompanyFinancilasAsync(simId);

            if (companyFinancials == null || companyFinancials.Count == 0)
            {
                return(false);
            }
            var cfMdl   = new List <CompanyFinancialsMd>();
            var oldcfML = _dbconCompany.Get(o => o.SimId.Equals(simId)).ToList();

            foreach (var(companyFinancial, oldcf) in from companyFinancial in companyFinancials
                     let oldcf = oldcfML.Where(o => o.SimId.Equals(companyFinancial.SimId) &&
                                               o.FYear == companyFinancial.FYear &&
                                               o.Statement == companyFinancial.Statement).FirstOrDefault()
                                 select(companyFinancial, oldcf))
            {
                cfMdl.Add(new CompanyFinancialsMd(companyFinancial));
                if (oldcf != null)
                {
                    cfMdl.Last().Id = oldcf.Id;
                }
            }

            try
            {
                var returnValue = await _dbconCompany.UpdateMultiple(cfMdl);

                if (returnValue == false)
                {
                    return(false);
                }
                await RemoveUnwantedRecords(cfMdl, oldcfML);

                returnValue = await _hcl.UpdateCompanyDetailAsync(simId, cfMdl.First().IndustryTemplate);

                return(returnValue);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error in method HandleFinacials:UpdateStatments\n{ex.Message}");
                return(false);
            }
        }
예제 #5
0
        private LastUpateCollectionMd GetSymbolsFromDb()
        {
            LastUpateCollectionMd lastUpdateDate = _connectionHandlerLU.Get(r => r.CollectionName.Equals(SecSymobls)).FirstOrDefault();

            if (lastUpdateDate != null && lastUpdateDate.LastUpdate >= DateTime.Now.AddDays(-1))
            {
                var symbolsMd = _connectionHandlerSS.Get().ToList();
                if (symbolsMd != null && symbolsMd.Any())
                {
                    symbols = _mapper.Map <List <SecuritySymbol> >(symbolsMd);
                }
            }
            return(lastUpdateDate);
        }
        public async Task <string> GetCompanyFundamentals(string companyName)
        {
            _logger.LogTrace("Starting fundamental details");
            var tickersToUse = await _resolveCompanyName.ResolveCompanyNameOrTicker(companyName);

            if (tickersToUse.IsNullOrWhiteSpace())
            {
                return($"We could not resolve ticker/company Name {companyName}; possible reason Google registered name is Alphabet Inc.\n\n" +
                       $"Hint: try with symbol or ticker");
            }
            var fulfillmentText = new StringBuilder();

            try
            {
                int counter = 0;
                foreach (var ticker in tickersToUse.Split(','))
                {
                    var ratingsMd = _connectionHandlerCF.Get().Where(x => x.Ticker.ToLower().Equals(ticker.ToLower()))
                                    .OrderByDescending(x => x.FYear).FirstOrDefault();
                    PiotroskiScore computedRating = null;

                    if (ratingsMd != null && DateTime.Now.Year - ratingsMd.FYear <= 2)
                    {
                        computedRating = _mapper.Map <PiotroskiScore>(ratingsMd);
                    }
                    fulfillmentText.Append(await BuildCompanyProfile(ticker, computedRating));
                    if (++counter >= 2)
                    {
                        break;
                    }
                }
                if (counter >= 2)
                {
                    fulfillmentText.Append($"Limiting result set as the search term {companyName} resolved to too many results.\n");
                }
            }
            catch (Exception ex)
            {
                _logger.LogCritical($"Error while processing Get Company Fundamentals; \n{ex.Message}");
                return("");
            }
            if (fulfillmentText.ToString().Contains("Piotroski"))
            {
                fulfillmentText.Append("\nNote: Piotroski F-Score is based on company fundamentals; " +
                                       "a rating greater than 6 indicates strong fundamentals.");
            }
            return(fulfillmentText.ToString());
        }
예제 #7
0
        /// <summary>
        /// Gets the out standing shares.
        /// </summary>
        /// <param name="simId">The sim identifier.</param>
        /// <returns></returns>
        public async Task <OutstandingShares> GetOutStandingShares(string simId)
        {
            var existingRecord = _dBConnection.Get(x => x.SimId == simId).FirstOrDefault();

            if (existingRecord != null &&
                existingRecord.LastUpdateDate != null &&
                ((TimeSpan)(DateTime.Now - existingRecord.LastUpdateDate)).Days < validityOfRecord)
            {
                return(Mapper.Map <OutstandingSharesMd, OutstandingShares>(existingRecord));
            }
            var externalData = await _dos.ObtainAggregatedList(simId);

            if (externalData == null)
            {
                _logger.LogError($"Could not download outstanding shares for SimId:{simId}");
                return(null);
            }
            string id = "";

            if (existingRecord != null)
            {
                id = existingRecord.Id;
            }
            existingRecord = Mapper.Map <OutstandingShares, OutstandingSharesMd>(externalData);
            existingRecord.LastUpdateDate = DateTime.Now;
            if (!id.IsNullOrWhiteSpace())
            {
                existingRecord.Id = id;
                await _dBConnection.Update(id, existingRecord);
            }
            else
            {
                await _dBConnection.Create(existingRecord);
            }
            return(externalData);
        }
예제 #8
0
        public async Task <WebhookResponse> GetCompanyRatings(GoogleCloudDialogflowV2WebhookRequest ratingsParameters)
        {
            _log.LogTrace("Start obtain fundamentals");
            var companyNameToResolve = ratingsParameters.QueryResult.Parameters[companyName].ToString();
            var tickersToUse         = await _obtainCompanyDetails.ResolveCompanyNameOrTicker(companyNameToResolve);

            if (string.IsNullOrWhiteSpace(tickersToUse))
            {
                return(new WebhookResponse
                {
                    FulfillmentText = $"Could not resolve {companyNameToResolve}"
                });
            }

            var fulfillmentText = new StringBuilder();

            try
            {
                int counter = 0;
                foreach (var ticker in tickersToUse.Split(','))
                {
                    var computedRatingMd = _connectionHandlerCF.Get().Where(x => x.Ticker.ToLower().Equals(ticker.ToLower()) &&
                                                                            x.FYear == DateTime.Now.Year).FirstOrDefault();
                    if (computedRatingMd == null)
                    {
                        computedRatingMd = _connectionHandlerCF.Get().Where(x => x.Ticker.ToLower().Equals(ticker.ToLower()) &&
                                                                            x.FYear == DateTime.Now.Year - 1).FirstOrDefault();
                    }
                    PiotroskiScore computedRating = null;
                    if (computedRatingMd != null)
                    {
                        computedRating = Mapper.Map <PiotroskiScore>(computedRatingMd);
                    }
                    fulfillmentText.Append(await BuildCompanyProfile(ticker, computedRating));
                    if (++counter >= 2)
                    {
                        break;
                    }
                }
                if (counter >= 2)
                {
                    fulfillmentText.Append($"Limiting result set as the search term {companyNameToResolve} resolved to too many results.\n");
                }
            }
            catch (Exception ex)
            {
                _log.LogCritical($"Error while processing Getting Company Ratings; \n{ex.Message}");
                return(new WebhookResponse
                {
                    FulfillmentText = Utilities.ErrorReturnMsg() + Utilities.EndOfCurrentRequest()
                });
            }
            if (fulfillmentText.ToString().Contains("Piotroski"))
            {
                fulfillmentText.Append("Note: Piotroski F-Score is based on company fundamentals; " +
                                       "a rating greater than 6 indicates strong fundamentals");
            }
            var webhookResponse = new WebhookResponse
            {
                FulfillmentText = fulfillmentText.ToString()
            };

            _log.LogTrace("End obtain fundamentals");
            return(webhookResponse);
        }