Пример #1
0
        public async Task <Quote> GetQuote(string scrip)
        {
            // You could query multiple symbols with multiple fields through the following steps:
            var securities = await Yahoo.Symbols(scrip).Fields(Field.Symbol, Field.RegularMarketPrice, Field.FiftyTwoWeekHigh,
                                                               Field.RegularMarketDayHigh, Field.RegularMarketDayLow, Field.RegularMarketPreviousClose, Field.AverageDailyVolume10Day,
                                                               Field.RegularMarketVolume, Field.FiftyDayAverage, Field.FiftyDayAverageChange, Field.FiftyDayAverageChangePercent, Field.RegularMarketTime
                                                               ).QueryAsync();

            var sec = securities[scrip];

            //trend over past years
            var history = await Yahoo.GetHistoricalAsync(scrip, new DateTime(2019, 1, 1), new DateTime(2020, 4, 1), Period.Monthly);

            Quote myQuote = new Quote();

            myQuote.Scrip           = sec.Symbol;
            myQuote.MktTime         = sec.RegularMarketTime;
            myQuote.Currentprice    = sec.RegularMarketPrice;
            myQuote.High            = sec.RegularMarketDayHigh;
            myQuote.Low             = sec.RegularMarketDayLow;
            myQuote.Volume          = sec.RegularMarketVolume;
            myQuote.Avg10DVolume    = sec.AverageDailyVolume10Day;
            myQuote.FiftyDayAverage = sec.FiftyDayAverage;
            myQuote.PreviousClose   = sec.RegularMarketPreviousClose;
            myQuote.History         = history;

            return(myQuote);
        }
        public async Task <object> Get(string s)
        {
            var now     = DateTime.UtcNow;
            var from    = now.AddDays(-7);
            var markets = new[] { "SPY", s };
            var t       = markets
                          .Select(async s => new { m = s, d = await Yahoo.GetHistoricalAsync(s, from, now) })
                          .ToArray();

            var data = (await Task
                        .WhenAll(t))
                       .ToDictionary(s => s.m, s => GetPerformance(q => q.AdjustedClose, s.d));

            await Context.AddAsync(new Market
            {
                Date       = now,
                MarketId   = s,
                ProviderId = "Yahoo",
                Response   = JsonConvert.SerializeObject(data)
            });

            await Context.SaveChangesAsync();

            return(data);
        }
Пример #3
0
        private async Task GetPrices()
        {
            IReadOnlyList <YahooFinanceApi.Candle>
            results = await Yahoo.GetHistoricalAsync(cbStockAbbreviations.Text, new DateTime(2000, 1, 1),
                                                     DateTime.Now, Period.Daily, new System.Threading.CancellationToken());

            this.chart1.Series.Clear();

            this.chart1.Titles.Add("");

            Series series = this.chart1.Series.Add(cbStockAbbreviations.Text);

            series.ChartType = SeriesChartType.Spline;

            Series seriesFit = this.chart1.Series.Add($"{cbStockAbbreviations.Text} - FIT");

            seriesFit.ChartType = SeriesChartType.Spline;

            double[] x  = results.Select(r => (double)r.DateTime.Ticks).ToArray();
            double[] y  = results.Select(r => (double)r.Close).ToArray();
            double[] p  = Exponential(x, y); // a=1.017, r=0.687
            double[] yh = Generate.Map(x, k => p[0] * Math.Exp(p[1] * k));

            for (int c = 0; c < results.Count(); c++)
            {
                Candle candle = results[c];

                seriesFit.Points.AddXY(candle.DateTime, yh[c]);

                series.Points.AddXY(candle.DateTime, candle.Close);
            }
        }
 private void GetHistoricalQuotesInfoAsync()
 {
     try
     {
         var task = Task.Run(() =>
                             Yahoo.GetHistoricalAsync(CurrentSticker, DateTime.Now.AddMonths(-12), DateTime.Now, Period.Daily));
         task.Wait();
         var historicalData = task.Result;
         HistoricalQuotes = new List <Quote>();
         foreach (var item in historicalData)
         {
             HistoricalQuotes.Add(new Quote
             {
                 Close  = item.Close,
                 Open   = item.Open,
                 Date   = item.DateTime,
                 High   = item.High,
                 Low    = item.Low,
                 Volume = item.Volume
             });
         }
     }
     catch (Exception ex)
     {
         throw new Exception($"Failed to Get Historical Quotes Info. {ex.Message}");
     }
 }
        public async Task <List <StockModel> > GetGainerLooserStockData(string ticker = "",
                                                                        string period = "")
        {
            var p = Period.Daily;

            if (period.ToLower() == "weekly")
            {
                p = Period.Weekly;
            }
            else if (period.ToLower() == "monthly")
            {
                p = Period.Monthly;
            }
            var startDate = DateTime.Now.AddMonths(-11);
            var endDate   = DateTime.Now;
            var query     = await Yahoo.GetHistoricalAsync(ticker, startDate, endDate, p);

            List <StockModel> models = new List <StockModel>();

            foreach (var r in query)
            {
                models.Add(new StockModel
                {
                    StockName = ticker,
                    Date      = r.DateTime.ToString("yyyy-MM-dd"),
                    Open      = r.Open,
                    High      = r.High,
                    Low       = r.Low,
                    Close     = r.Close,
                    Volume    = r.Volume
                });
            }
            return(models);
        }
        public static async Task <List <YahooStockData> > GetYahooStock(string ticker, string start, string end, string period)
        {
            var p = Period.Daily;

            if (period.ToLower() == "weekly")
            {
                p = Period.Weekly;
            }
            else if (period.ToLower() == "monthly")
            {
                p = Period.Monthly;
            }
            var startDate = DateTime.Parse(start);
            var endDate   = DateTime.Parse(end);
            var hist      = await Yahoo.GetHistoricalAsync(ticker, startDate, endDate, p);

            List <YahooStockData> prices = new List <YahooStockData>();

            foreach (var r in hist)
            {
                prices.Add(new YahooStockData
                {
                    Ticker   = ticker,
                    Date     = r.DateTime,
                    Open     = (double)r.Open,
                    High     = (double)r.High,
                    Low      = (double)r.Low,
                    Close    = (double)r.Close,
                    CloseAdj = (double)r.AdjustedClose,
                    Volume   = r.Volume
                });
            }
            return(prices);
        }
Пример #7
0
        static async Task <List <CLASS_Ticker_DataBase> > LIST_Get_Database_Of_Ticker(string Ticker, double DaysToGoBack = 60)
        {
            List <CLASS_Ticker_DataBase> LIST_DATABase = new List <CLASS_Ticker_DataBase>();

            Yahoo.IgnoreEmptyRows = true;

            if (DaysToGoBack < 0)
            {
                DaysToGoBack = -1 * DaysToGoBack;
            }

            IReadOnlyList <Candle> Data = await Yahoo.GetHistoricalAsync(Ticker, DateTime.Today.AddDays(-1 * DaysToGoBack), DateTime.Today, Period.Daily);

            CLASS_Ticker_DataBase OBJECT_DataBase_Day = new CLASS_Ticker_DataBase();

            foreach (Candle Date in Data)
            {
                OBJECT_DataBase_Day       = new CLASS_Ticker_DataBase();
                OBJECT_DataBase_Day.Date  = Date.DateTime;
                OBJECT_DataBase_Day.Open  = Decimal.ToDouble(Date.Open);
                OBJECT_DataBase_Day.Close = Decimal.ToDouble(Date.Close);
                OBJECT_DataBase_Day.High  = Decimal.ToDouble(Date.High);
                OBJECT_DataBase_Day.Low   = Decimal.ToDouble(Date.Low);
                LIST_DATABase.Add(OBJECT_DataBase_Day);
            }

            return(LIST_DATABase);
        }
Пример #8
0
        static async Task Archivess()
        {
            // Sometimes, yahoo returns broken rows for historical calls, you could decide if these invalid rows is ignored or not by the following statement
            Yahoo.IgnoreEmptyRows = true;



            object securities;
            // You could query multiple symbols with multiple fields through the following steps:
            await Task.Run(() => securities = Yahoo.Symbols("TRCH", "GOOG").Fields(Field.Symbol, Field.RegularMarketPrice, Field.RegularMarketDayLow, Field.RegularMarketOpen, Field.RegularMarketPreviousClose).QueryAsync());

            //var TRCH = securities["TRCH"];
            //var price = TRCH[Field.RegularMarketPrice]; // or, you could use aapl.RegularMarketPrice directly for typed-value



            var testo = await Yahoo.Symbols("TRCH").Fields(Field.RegularMarketPrice, Field.RegularMarketDayLow, Field.RegularMarketOpen, Field.RegularMarketDayHigh).QueryAsync();



            // You should be able to query data from various markets including US, HK, TW
            // The startTime & endTime here defaults to EST timezone
            var history = await Yahoo.GetHistoricalAsync("SI", DateTime.Today.AddDays(-60), DateTime.Today, Period.Daily);

            foreach (var candle in history)
            {
                Console.WriteLine($"DateTime: {candle.DateTime}, Open: {candle.Open}, High: {candle.High}, Low: {candle.Low}, Close: {candle.Close}, Volume: {candle.Volume}, AdjustedClose: {candle.AdjustedClose}");
            }
        }
Пример #9
0
        /// <summary>
        /// Gets historical prices from Yahoo Finance given the specified configuration.
        /// </summary>
        /// <param name="config">Configuration parameters used to retrieve historical price data.</param>
        /// <returns></returns>
        public async Task <List <StockData> > GetPricesAsync(IHistoryConfig config)
        {
            string yahooSymbol = config.Ticker.ToString();
            Period yahooPeriod = YahooHistoryConfig.GetYahooPeriod(config.TimeFrame);

            IReadOnlyList <Candle> hist = await Yahoo.GetHistoricalAsync(
                yahooSymbol, config.DateFrom, config.DateTo, yahooPeriod);

            List <StockData> prices = new List <StockData>();

            foreach (Candle candle in hist)
            {
                prices.Add(new StockData()
                {
                    Ticker   = yahooSymbol,
                    Date     = candle.DateTime,
                    Open     = (double)candle.Open,
                    High     = (double)candle.High,
                    Low      = (double)candle.Low,
                    Close    = (double)candle.Close,
                    CloseAdj = (double)candle.AdjustedClose,
                    Volume   = candle.Volume
                });
            }
            return(prices);
        }
Пример #10
0
        private async Task DownloadFileAsync(DataRow row)
        {
            try
            {
                using (WebClient webClient = new WebClient())
                {
                    var history = await Yahoo.GetHistoricalAsync(row[2].ToString(), new DateTime(
                                                                     parent.SelectedDateFrom.Year,
                                                                     parent.SelectedDateFrom.Month,
                                                                     parent.SelectedDateFrom.Day), new DateTime(
                                                                     parent.SelectedDateTo.Year,
                                                                     parent.SelectedDateTo.Month,
                                                                     parent.SelectedDateTo.Day), Period.Daily);

                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine("Date;Close;Volume");
                    foreach (var item in history)
                    {
                        sb.AppendLine(string.Format("{0};{1};{2}",
                                                    item.DateTime.ToString("dd/MM/yyyy", CultureInfo.GetCultureInfo("fr-FR")),
                                                    item.Close,
                                                    item.Volume));
                    }
                    File.WriteAllText(Path.Combine(parent.FolderForStoringFilesLabelData, row[1] + ".csv"), sb.ToString());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Something wrong");
            }
        }
Пример #11
0
    static void Main(string[] args)
    {
        IList <Candle> candles;

        string[] symbols = new string[] { "AAPL", "GOOG", "MSFT", "NVDA", "AMAT", "ATVI" };
        //Parallel.For(0, 5, i =>
        //{
        //    Console.WriteLine($"Start {symbols[i]}");
        //    candles = Yahoo.GetHistoricalAsync(symbols[i], new DateTime(2016, 1, 1), period: Period.Daily).Result;
        //    Console.WriteLine($"{symbols[i]} - O: {candles.Last().Open}, H: {candles.Last().High}, L: {candles.Last().Low}, C: {candles.Last().Close}");
        //    var divList = Yahoo.GetHistoricalDividendsAsync(symbols[i]).Result;
        //    Console.WriteLine("{0}: {1}", symbols[i],  divList.Any() ? divList.Last().DateTime.ToString() : "None");
        //});

        candles = Yahoo.GetHistoricalAsync("^GSPC", new DateTime(2016, 1, 1), period: Period.Daily).Result;

        //var list = Yahoo
        //   .Symbol("VAW")
        //   .Tag(Tag.LastTradePriceOnly, Tag.ChangeAndPercentChange, Tag.DaysLow, Tag.DaysHigh)
        //   .GetAsync()
        //   .Result;
        //var aapl = list["VAW"];
        //Console.WriteLine(aapl[Tag.LastTradePriceOnly]);
        Console.ReadLine();
    }
Пример #12
0
        public static async Task <IReadOnlyList <Candle> > GetHistoryAsync(string symbol, int days)
        {
            // You should be able to query data from various markets including US, HK, TW
            // The startTime & endTime here defaults to EST timezone
            var history = await Yahoo.GetHistoricalAsync(symbol, DateTime.Now.AddDays(-1 * (days + 1)), DateTime.Now, Period.Daily);

            return(history);
        }
Пример #13
0
        public async Task <List <Candle> > GetHistoricalAsyn(string symbol, DateTime from, DateTime to)
        {
            var history = await Yahoo.GetHistoricalAsync("XELA", new DateTime(2016, 1, 1), new DateTime(2020, 7, 1), Period.Daily);

            var aaa = Yahoo.Symbols();

            return(history.ToList());
        }
Пример #14
0
        public void MainLogic()
        {
            // Get the Symbol List
            LoadByCategory();

            // Overall Analysis
            foreach (var item in alls)// for each symbol
            {
                try
                {
                    var securities = Yahoo.Symbols(item.Key).Fields(Field.TrailingPE).QueryAsync().Result;
                    item.Value.TrailingPE = securities[item.Key].TrailingPE;
                }
                catch (Exception e)
                {
                    if (e.Message == "The given key was not present in the dictionary.")
                    {
                        continue;
                    }
                    throw;
                }
            }

            // Get their history data and generate feature
            foreach (var item in interested)// for each symbol
            {
                item.Value.HisData.Add(Yahoo.GetHistoricalAsync(item.Key, DateTime.Now.AddYears(-1 * lookBackYear), DateTime.Now).Result.ToList());

                CurrentPriceAnalysis(item);

                CycleAnlaysis(item);

                item.Value.Prepare();// Prepare to show
            }

            // Prepare the bought stocks data

            using (StreamReader sr = new StreamReader(File.OpenRead("Bought.txt")))
            {
                while (!sr.EndOfStream)
                {
                    string symbol = sr.ReadLine();
                    interested[symbol].IBoughtPrice            = double.Parse(sr.ReadLine());
                    interested[symbol].IBoughtAmount           = double.Parse(sr.ReadLine());
                    interested[symbol].IBoughtDate             = new DateTime(int.Parse(sr.ReadLine()), int.Parse(sr.ReadLine()), int.Parse(sr.ReadLine()));
                    interested[symbol].CurrentProfitPercentage = Math.Round(((double)interested[symbol].HisData[0].Last().Close - interested[symbol].IBoughtPrice) / interested[symbol].IBoughtPrice * 100, 2);
                    for (int i = 0; i < 7; i++)
                    {
                        double yes    = (double)interested[symbol].HisData[0][interested[symbol].HisData[0].Count - 1 - i].Close;
                        double yesyes = (double)interested[symbol].HisData[0][interested[symbol].HisData[0].Count - 2 - i].Close;
                        interested[symbol].ProfitPercentageComparedToBefore.Add(Math.Round((yes - yesyes) / yesyes * 100, 2));
                    }
                    interested[symbol].CurrentProfitAmount = Math.Round(interested[symbol].CurrentProfitPercentage * interested[symbol].IBoughtAmount * interested[symbol].IBoughtPrice / 100, 2);
                    interested[symbol].Bought = true;
                    bought.Add(symbol, interested[symbol]);
                }
            }
        }
Пример #15
0
        public IReadOnlyList <Candle> GetSecurityHistoricData(string symbol, DateTime startDate, DateTime endDate)
        {
            _logger.Information($"YahooFinanceApiManager: Retrieving historic data for {symbol} between {startDate.ToString("yyyy-MM-dd")}" +
                                $" and {endDate.ToString("yyyy-MM-dd")}");

            Task <IReadOnlyList <Candle> > dataTask = Yahoo.GetHistoricalAsync(symbol, startDate, endDate, Period.Daily);

            dataTask.Wait();

            return(dataTask?.Result);
        }
Пример #16
0
        public async Task <IEnumerable <Candle> > GetHistoricalQuotes()
        {
            return(await Yahoo.GetHistoricalAsync("AAPL", new DateTime(2018, 12, 1), DateTime.Now, Period.Daily));

            //foreach (var candle in history)
            //{
            //    Console.WriteLine($"DateTime: {candle.DateTime}, Open: {candle.Open}, High: {candle.High}, Low: {candle.Low}, Close: {candle.Close}, Volume: {candle.Volume}, AdjustedClose: {candle.AdjustedClose}");
            //}

            // return history.ToList();
        }
Пример #17
0
        public async System.Threading.Tasks.Task <IReadOnlyList <Candle> > GetDataAsync(Tuple <DateTime, DateTime> dates)
        {
            var ticker    = "???"; // TODO:  enter stock ticker symbol
            var frequency = Period.Daily;
            var startDate = dates.Item1;
            var endDate   = dates.Item2;

            var data = await Yahoo.GetHistoricalAsync(ticker, startDate, endDate, frequency);

            return(data);
        }
Пример #18
0
        public async void DownloadYFtoCsv()
        {
            ReadTickerUniverse();
            foreach (var ticker in m_universeTickers)
            {
                DateTime expectedHistoryStartDateET = new DateTime(2010, 1, 1);
                IReadOnlyList <Candle?>?history     = await Yahoo.GetHistoricalAsync(ticker, expectedHistoryStartDateET, DateTime.Now, Period.Daily);

                YFRecord[] yfRecords = history.Select(r => new YFRecord()
                {
                    Date = Utils.Date2hYYYYMMDD(r !.DateTime), AdjClose = RowExtension.IsEmptyRow(r !) ? float.NaN : (float)Math.Round(r !.AdjustedClose, 4), Close = RowExtension.IsEmptyRow(r !) ? float.NaN : (float)Math.Round(r !.Close, 4)
                }).ToArray();
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            var quoteMaker = new QuoteMaker(new InvestipsQuoteBuilder());

            var httpClient = GetHttpClient();

            var symbols = await GetStockSymbols(httpClient);

            foreach (var symbol in symbols)
            {
                var history = await Yahoo.GetHistoricalAsync(symbol, new DateTime(2018, 1, 1), DateTime.Now, Period.Daily);

                quoteMaker.BuildQuote(history, symbol);
                var quote = quoteMaker.GetQuotes();
            }

            var quoteService  = new QuoteService();
            var historyQuotes = await quoteService.GetHistoricalQuotes();



            var mvAvgs10Info = GetMovingAveragesByPeriod(historyQuotes, 10);

            log.Info("C# HTTP trigger function processed a request.");


            // parse query parameter
            string name = req.GetQueryNameValuePairs()
                          .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
                          .Value;

            if (name == null)
            {
                // Get request body
                dynamic data = await req.Content.ReadAsAsync <object>();

                name = data?.name;
            }

            using (var db = new InvestipsQuotesContext())
            {
                db.Quotes.Add(new Quote {
                    Symbol = "AAPL", Open = 100, High = 103, Low = 99, Close = 102, TimeStampDateTime = DateTime.Now
                });
                await db.SaveChangesAsync();

                log.Info("Quote Created");
            }

            return(name == null
                ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
                : req.CreateResponse(HttpStatusCode.OK, "Hello " + name));
        }
Пример #20
0
        public async Task <Acao> GetAsync(string simboloAcao)
        {
            var retorno   = new Acao();
            var resultado = await Yahoo.GetHistoricalAsync(simboloAcao, DateTime.Now.AddMonths(-1), DateTime.Now, Period.Daily);

            foreach (var pregao in resultado)
            {
                retorno.Historico.Add(new Historico(pregao.DateTime, pregao.Open));
            }

            retorno.CalcularVariacoes();
            return(retorno);
        }
Пример #21
0
        /// <summary>
        /// Imports the async. Endtime stock history exclusive
        /// </summary>
        /// <returns>The async.</returns>
        /// <param name="symbol">Symbol.</param>
        /// <param name="startTime">Start time.</param>
        /// <param name="endTime">End time.</param>
        /// <param name="period">Period.</param>
        /// <param name="token">Token.</param>
        public async Task <IList <Core.Candle> > ImportAsync(string symbol, DateTime?startTime = default(DateTime?), DateTime?endTime = default(DateTime?), PeriodOption period = PeriodOption.Daily, CancellationToken token = default(CancellationToken))
        {
            if (period != PeriodOption.Daily && period != PeriodOption.Weekly && period != PeriodOption.Monthly)
            {
                throw new ArgumentException("This importer only supports daily, weekly & monthly data");
            }

            var corrStartTime = (startTime < UnixMinDateTime ? UnixMinDateTime : startTime) ?? UnixMinDateTime;
            var corrEndTime   = (endTime > UnixMaxDateTime ? UnixMaxDateTime : endTime) ?? UnixMaxDateTime;
            var candles       = await Yahoo.GetHistoricalAsync(symbol, corrStartTime, corrEndTime, PeriodMap[period], false, token);

            return(candles.Select(c => new Core.Candle(c.DateTime, c.Open, c.High, c.Low, c.Close, c.Volume)).OrderBy(c => c.DateTime).ToList());
        }
Пример #22
0
        public async void RunMethods()
        {
            try
            {
                var history = await Yahoo.GetHistoricalAsync("XELA", null, DateTime.Now, Period.Daily);

                var x = history;
                ///var history1 = await Yahoo.GetHistoricalAsync("XELA", new DateTime(2016, 1, 1), new DateTime(2020, 7, 1), Period.Daily);
                //var history2 = await Yahoo.GetHistoricalAsync("XELA", new DateTime(2000, 1, 1), new DateTime(2020, 7, 1), Period.Daily);
            }
            catch (Exception exc)
            {
            }
        }
Пример #23
0
        public async Task <List <StockPriceModel> > GetStockData(string ticker, string start,
                                                                 string end, string period)
        {
            DateTime startDate = DateTime.Now.AddYears(-1);
            DateTime endDate   = DateTime.Now;
            var      p         = Period.Daily;

            if (period.ToLower() == "weekly")
            {
                p = Period.Weekly;
            }
            else if (period.ToLower() == "monthly")
            {
                p = Period.Monthly;
            }

            if (start != null && end != null)
            {
                startDate = DateTime.Parse(start);
                endDate   = DateTime.Parse(end);
            }


            var hist = await Yahoo.GetHistoricalAsync(ticker, startDate, endDate, p);

            List <StockPriceModel> models = new List <StockPriceModel>();

            foreach (var r in hist)
            {
                models.Add(new StockPriceModel
                {
                    Ticker        = ticker,
                    Date          = r.DateTime.ToString("yyyy-MM-dd"),
                    Open          = r.Open,
                    High          = r.High,
                    Low           = r.Low,
                    Close         = r.Close,
                    AdjustedClose = r.AdjustedClose,
                    Volume        = r.Volume
                });
            }


            //

            return(models);
        }
Пример #24
0
        public async Task <Equity> ImportAsync(string symbol, DateTime?startTime = default(DateTime?), DateTime?endTime = default(DateTime?), PeriodOption period = PeriodOption.Daily, CancellationToken token = default(CancellationToken))
        {
            if (period != PeriodOption.Daily && period != PeriodOption.Weekly && period != PeriodOption.Monthly)
            {
                throw new ArgumentException("This importer only supports daily, weekly & monthly data");
            }

            var yahooCandles = await Yahoo.GetHistoricalAsync(symbol, startTime, endTime, _periodMap[period], false, token);

            var output = new List <Core.Candle>();

            foreach (var yahooCandle in yahooCandles)
            {
                output.Add(new Core.Candle(yahooCandle.DateTime, yahooCandle.Open, yahooCandle.High, yahooCandle.Low, yahooCandle.Close, yahooCandle.Volume));
            }

            return(output.ToEquity(symbol, period));
        }
Пример #25
0
        public async Task <List <Candle> > GetHistoricalCandles(string symbol, DateTime?from, DateTime to)
        {
            List <Candle> list = new List <Candle>();

            try
            {
                var history = await Yahoo.GetHistoricalAsync(symbol, from, to, Period.Daily);

                if (history.Count > 0)
                {
                    list = history.ToList();
                }
            }
            catch (Exception exc)
            {
            }
            return(list);
        }
Пример #26
0
        public async Task <ICollection <ApiHistory> > GetFullHistory(string symbol)
        {
            symbol = symbol.ToUpper();
            var result = await Yahoo.GetHistoricalAsync(symbol, new DateTime(2000, 1, 1),
                                                        DateTime.UtcNow);

            var models = result.Select(x => new ApiHistory
            {
                Volume   = x.Volume,
                Low      = (double)x.Low,
                High     = (double)x.High,
                Open     = (double)x.Open,
                Close    = (double)x.Close,
                DateTime = x.DateTime
            }).ToArray();

            return(models);
        }
        //public async Task Load()
        //{
        //"MGLU3.SA"
        //var result = await Yahoo.GetHistoricalAsync("MGLU3.SA", new DateTime(2011, 05, 01), DateTime.Now, Period.Daily);

        //HistoricalPrice.AddRange(result.Where(a => a.Close != 0).ToList().ConvertAll(a => PBL_YahooFinance.BLL.Converter.ItemToFileHelperDto(a)));

        //var closePrice = result.Where(a => a.Close != 0).Select(a => a.Close).ToList();
        //var dateArray = result.Where(a => a.Close != 0).Select(a => a.DateTime.ToString("MM/dd/yyyy")).ToArray();

        //await LoadChart(closePrice, dateArray);

        //RaiseAllCanExecuteChanged();
        //}

        private async Task LoadHistoricalPrice()
        {
            StatusMessage = "Status: Loading...";
            var result = await Yahoo.GetHistoricalAsync(LoadAsset, StartDate, EndDate, Period.Daily);

            HistoricalPrice.Clear();
            HistoricalPrice.AddRange(result.Where(a => a.Close != 0)
                                     .OrderByDescending(a => a.DateTime)
                                     .ToList()
                                     .ConvertAll(a => PBL_YahooFinance.BLL.Converter.ItemToFileHelperDto(a)));

            var closePrice = result.Where(a => a.Close != 0).Select(a => a.Close).ToList();
            var dateArray  = result.Where(a => a.Close != 0).Select(a => a.DateTime.ToString("MM/dd/yyyy")).ToArray();

            await LoadChart(closePrice, dateArray);

            RaiseAllCanExecuteChanged();
            StatusMessage = "Status: Success.";
        }
Пример #28
0
        public static async Task DownloadEodAsync()
        {
            var symbols = DbHelper.GetUsaStockSymbols("select symbol from UsaStock");

            symbols.Add("%5ENDX"); //nsdaq 100 index, that is, _ndx
            Yahoo.IgnoreEmptyRows = true;
            var batchSize        = 100;
            var totalSymbolCount = symbols.Count();
            //totalSymbolCount = 5;
            var startDate    = DateTime.Now.AddDays(-15); //will download upto 15 days old data
            var latestDbDate = DbHelper.GetLatestEodDate() ?? DateTime.Now.AddDays(-100);

            startDate = (latestDbDate > startDate) ? latestDbDate.AddDays(1) : startDate;

            //var isValid = DateTime.TryParse("2019-06-18 00:00:00.000", out startDate);


            foreach (var symbol in symbols)
            {
                IReadOnlyList <Candle> history = null;
                // You should be able to query data from various markets including US, HK, TW
                // The startTime & endTime here defaults to EST timezone
                try
                {
                    history = await Yahoo.GetHistoricalAsync(symbol, startDate, DateTime.Now, Period.Daily);
                }
                catch (Exception ex)
                {
                }

                if (history != null)
                {
                    DbHelper.SaveToDatabase(history, symbol);
                    //foreach (var candle in history)
                    //{
                    //    Console.WriteLine($"DateTime: {candle.DateTime}, Open: {candle.Open}, High: {candle.High}, Low: {candle.Low}, Close: {candle.Close}, Volume: {candle.Volume}, AdjustedClose: {candle.AdjustedClose}");
                    //}
                }
            }
        }
Пример #29
0
        protected async void insert(string symbol, DateTime begin, DateTime end)
        {
            try
            {
                string symbols = symbol;



                var history = await Yahoo.GetHistoricalAsync(symbols, begin, end, Period.Daily);

                LB_Symbol.Text = symbols;
                clearDatabase();

                foreach (var candle in history)
                {
                    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["StockConnectionDB"].ConnectionString);
                    con.Open();
                    string     insert = "insert into stock (symbols, openstock, High, Low, Closestock, Volume, AdjustedClose, DateTime) values(@symbols, @openstock, @High, @Low, @Closestock, @Volume, @AdjustedClose, @DateTime)";
                    SqlCommand cmd    = new SqlCommand(insert, con);
                    cmd.Parameters.AddWithValue("@symbols", symbols);
                    cmd.Parameters.AddWithValue("@openstock", candle.Open);
                    cmd.Parameters.AddWithValue("@High", candle.High);
                    cmd.Parameters.AddWithValue("@Low", candle.Low);
                    cmd.Parameters.AddWithValue("@Closestock", candle.Close);
                    cmd.Parameters.AddWithValue("@Volume", candle.Volume);
                    cmd.Parameters.AddWithValue("@AdjustedClose", candle.AdjustedClose);
                    cmd.Parameters.AddWithValue("@DateTime", candle.DateTime);
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
            catch (Exception ex)
            {
                //Response.Redirect("Error.aspx");
                //ClientScript.RegisterStartupScript(this.GetType(), "Fehler", "alert('" + ex.Message + "');", true);
                Response.Write("<script>alert('Symbol konnte nicht gefunden werden');</script>");
            }
        }
        public List <StockModel> GetDashboardPortfolioData()
        {
            _StockDbEntities = new StockDbEntities();
            var stockmasters = _StockDbEntities.StockMasters.Where(x => x.IsActive == true).ToList();
            List <StockModel> stockModels = new List <StockModel>();

            stockmasters.ForEach(x => {
                var period = "daily";
                var p      = Period.Daily;
                if (period.ToLower() == "weekly")
                {
                    p = Period.Weekly;
                }
                else if (period.ToLower() == "monthly")
                {
                    p = Period.Monthly;
                }
                var startDate = DateTime.Now.AddDays(-3);
                var endDate   = DateTime.Now;

                var stockData = Yahoo.GetHistoricalAsync(x.StockId, startDate, endDate, p).Result;
                if (stockData.Count > 0)
                {
                    StockModel stockModel    = new StockModel();
                    var lastRecord           = stockData.LastOrDefault();
                    stockModel.StockId       = x.StockId;
                    stockModel.StockName     = x.StockName;
                    stockModel.BuyPrice      = x.BuyPrice;
                    stockModel.Qty           = x.Qty;
                    stockModel.TotalInvested = x.Qty * x.BuyPrice;
                    stockModel.CurrentValue  = x.Qty * (int)lastRecord.AdjustedClose;
                    stockModel.TotalGain     = stockModel.CurrentValue - stockModel.TotalInvested;
                    stockModels.Add(stockModel);
                }
            });
            return(stockModels.OrderBy(c => c.TotalGain).ToList());
        }