Ejemplo n.º 1
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);
        }
Ejemplo n.º 2
0
        public async Task TestQuoteAsync()
        {
            const string AAPL = "AAPL";

            var quote = await Yahoo.Symbols(AAPL).Fields(
                Field.RegularMarketOpen,
                Field.RegularMarketDayHigh,
                Field.RegularMarketDayLow,
                Field.RegularMarketPrice,
                Field.RegularMarketVolume,
                Field.RegularMarketTime)
                        .QueryAsync();

            var aaplQuote        = quote[AAPL];
            var aaplOpen         = aaplQuote[Field.RegularMarketOpen.ToString()];
            var aaplHigh         = aaplQuote[Field.RegularMarketDayHigh.ToString()];
            var aaplLow          = aaplQuote[Field.RegularMarketDayLow.ToString()];
            var aaplCurrentPrice = aaplQuote[Field.RegularMarketPrice.ToString()];
            var aaplVolume       = aaplQuote[Field.RegularMarketVolume.ToString()];
            var aaplTime         = aaplQuote[Field.RegularMarketTime.ToString()];

            // Get New York Timezone for conversion from UTC to New York Time for Yahoo Quotes
            TimeZoneInfo TzEst = TimeZoneInfo
                                 .GetSystemTimeZones()
                                 .Single(tz => tz.Id == "Eastern Standard Time" || tz.Id == "America/New_York");

            long     unixDate = 1568232001; // Any unix timestamp
            DateTime start    = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            DateTime date     = start.AddSeconds(unixDate);
            DateTime estDate  = TimeZoneInfo.ConvertTimeFromUtc(date, TzEst);
        }
Ejemplo n.º 3
0
 public YahooStockModel GetStockDetails()
 {
     try
     {
         StockDetails[] stocks = new StockDetails[2];
         Task <IReadOnlyDictionary <string, Security> > task    = Yahoo.Symbols("FOLD", "GOOG").Fields(Field.Symbol, Field.LongName, Field.RegularMarketPrice, Field.RegularMarketChangePercent).QueryAsync();
         IReadOnlyDictionary <string, Security>         results = task.Result;
         int index = 0;
         foreach (Security security in results.Values)
         {
             StockDetails stock = new StockDetails()
             {
                 StockCode     = security[Field.Symbol],
                 Description   = security[Field.LongName],
                 CurrentPrice  = security[Field.RegularMarketPrice],
                 MarketChanges = security[Field.RegularMarketChangePercent]
             };
             stocks[index] = stock;
             index++;
         }
         return(new YahooStockModel()
         {
             Stocks = stocks
         });
     }
     catch
     {
         throw new WebException(@"There is an ERROR using Yahoo Finance API.");
     }
 }
Ejemplo n.º 4
0
        public async Task <StockSummary> GetStockQuote(string ticker)
        {
            var securities = await Yahoo.Symbols(ticker).Fields(Field.LongName, Field.RegularMarketPrice, Field.RegularMarketChange, Field.RegularMarketChangePercent, Field.FiftyTwoWeekHigh, Field.FiftyTwoWeekLow, Field.RegularMarketDayLow, Field.RegularMarketDayHigh, Field.RegularMarketOpen, Field.RegularMarketPreviousClose, Field.RegularMarketVolume, Field.Bid, Field.BidSize, Field.Ask, Field.AskSize, Field.EarningsTimestamp, Field.EpsForward, Field.FinancialCurrency, Field.MarketCap).QueryAsync();

            var security = securities[ticker.ToUpper()];

            security.Fields.TryGetValue(ticker, out dynamic key);
            StockSummary models = new StockSummary()
            {
                Ticker        = ticker,
                Name          = security.LongName,
                Change        = security.RegularMarketChange,
                ChangePercent = security.RegularMarketChangePercent,
                weekHigh      = security.FiftyTwoWeekHigh,
                weekLow       = security.FiftyTwoWeekLow,
                dayHigh       = security.RegularMarketDayHigh,
                dayLow        = security.RegularMarketDayLow,
                Open          = Convert.ToDecimal(security.RegularMarketOpen),
                Close         = Convert.ToDecimal(security.RegularMarketPreviousClose),
                Bid           = security.Bid,
                Ask           = security.Ask,
                BidSize       = security.BidSize,
                AskSize       = security.AskSize,
                market        = security.MarketCap,
                Currency      = security.Currency,
                Volume        = security.RegularMarketVolume
            };

            return(models);
        }
Ejemplo n.º 5
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");
            }
        }
Ejemplo n.º 6
0
 public void Yahoo()
 {
     Yahoo yahoo = new Yahoo(driver);
     yahoo.goToSite();
     yahoo.sendWord();
     yahoo.headersToListFirstPage();
 }
Ejemplo n.º 7
0
        public static async Task DownloadAsync()
        {
            var symbols = DbHelper.GetUsaStockSymbols("select symbol from UsaStock");

            // You could query multiple symbols with multiple fields through the following steps:
            //var securities = await Yahoo.Symbols("AAPL", "GOOG").Fields(Field.Symbol, Field.RegularMarketPrice, Field.FiftyTwoWeekHigh).QueryAsync();
            // 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;
            var batchSize        = 100;
            var totalSymbolCount = symbols.Count();

            //totalSymbolCount = 5;

            for (var index = 0; index < totalSymbolCount; index += batchSize)
            {
                var currentSymbols = symbols.Skip(index).Take(batchSize);
                var securities     = await Yahoo.Symbols(currentSymbols.ToArray()).QueryAsync();

                DbHelper.SaveToDatabase(securities);

                //sleep for some time
                System.Threading.Thread.Sleep(2000);
            }


            //var securities = await Yahoo.Symbols("AAPL", "GOOG").QueryAsync();
            //var aapl = securities["AAPL"];
            //var price = aapl[Field.RegularMarketPrice]; // or, you could use aapl.RegularMarketPrice directly for typed-value
        }
Ejemplo n.º 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}");
            }
        }
Ejemplo n.º 9
0
        public void Setup()
        {
            ChromeDriverService service = ChromeDriverService.CreateDefaultService(@"F:\src\qa\qa_automation_lib", "chromedriver.exe");

            driver  = new ChromeDriver(service);
            webpage = new Yahoo(driver);
        }
Ejemplo n.º 10
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();
    }
Ejemplo n.º 11
0
 private void SpamYahoo(Yahoo yahoo)
 {
     if (yahoo.GoToSpamFolder())
     {
         //case 1
         if (read_not_spam.Checked)
         {
             while (yahoo.ReadNotSpam())
             {
                 Application.DoEvents();
             }
         }
         //case 2
         if (check_not_spam.Checked)
         {
             while (yahoo.CheckNotSpam())
             {
                 Application.DoEvents();
             }
         }
         //case 3
         if (ckeckall_not_spam.Checked)
         {
             while (yahoo.CheckAllNotSpam())
             {
                 Application.DoEvents();
             }
         }
     }
 }
Ejemplo n.º 12
0
        // Method to create the ticker from YahooFinance and add it to a list.
        private async void GetTicker(string name)
        {
            try
            {
                var securities = await Yahoo.Symbols(name).Fields(Field.Symbol, Field.RegularMarketPrice, Field.RegularMarketVolume, Field.RegularMarketOpen, Field.FiftyTwoWeekHigh).QueryAsync();

                var    aapl   = securities[name];
                Ticker ticker = new Ticker();
                ticker.Name      = name;
                ticker.CurrPrice = aapl.RegularMarketPrice;
                ticker.OpenPrice = aapl.RegularMarketOpen;
                ticker.Volume    = FormatNumber(aapl.RegularMarketVolume);
                tickerList.Add(ticker);
                this.tickerListView.Items.Add(ticker);
            }
            // Check if the symbol name is valid. If not remove from DB.
            catch
            {
                MessageBox.Show("Invalid Ticker symbol.");
                string query = "DELETE FROM Ticker WHERE Name=@Name";

                using (connection = new SqlConnection(connectionString))
                    using (SqlCommand command = new SqlCommand(query, connection))
                    {
                        connection.Open();
                        command.Parameters.AddWithValue("@Name", name);
                        command.ExecuteScalar();
                    }
            }
        }
Ejemplo n.º 13
0
        public async void YahooScrapper_ReturnsNotEmptyResult()
        {
            var yahooScrapper = new Yahoo();
            var result        = await yahooScrapper.Scrap("concurrency wiki");

            result.Should().NotBeNullOrEmpty();
        }
Ejemplo n.º 14
0
        public async Task TestQuery()
        {
            var securities = await Yahoo
                             .Symbols("C", "AAPL")
                             // Can use string field names:
                             .Fields("Bid", "Ask", "Tradeable", "LongName")
                             // and/or field enums:
                             .Fields(Field.RegularMarketPrice, Field.Currency)
                             .QueryAsync();

            Assert.Equal(2, securities.Count());
            var security = securities["C"];

            // Bid string or enum indexer returns dynamic type.
            security.Fields.TryGetValue("Bid", out dynamic bid);
            bid = security.Fields["Bid"];
            bid = security["Bid"];
            bid = security[Field.Bid];

            // Bid property returns static type.
            var bid2 = security.Bid;

            Assert.True(securities["C"][Field.Tradeable]);
            Assert.Equal("Apple Inc.", securities["AAPL"]["LongName"]);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Store the stock symbol in database for future retrieval.
        /// /// </summary>
        /// <param name="stockSymbol"></param>
        /// <returns></returns>
        public async Task <bool> StoreSymbolAsync(string stockSymbol)
        {
            IReadOnlyDictionary <string, Security> securities = new Dictionary <string, Security>();

            try {
                securities = await Yahoo.Symbols(stockSymbol).Fields(fieldList.ToArray()).QueryAsync();
            } catch {
                throw;
            }
            if (securities.Count.Equals(0))
            {
                throw new ArgumentException("Invalid stock symbol: " + stockSymbol);
            }
            var insNu = symbolCollection.Insert(new BsonDocument {
                ["Symbol"] = stockSymbol.ToUpper()
            });

            if (insNu != null)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 16
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 <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);
        }
Ejemplo n.º 18
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);
        }
Ejemplo n.º 19
0
        static async Task <List <CLASS_Ticker_Info> > LIST_Get_Tickers_Current_From_Array(string[] ARRAY_Input_Tickers)
        {
            List <CLASS_Ticker_Info> LIST_Tickers         = new List <CLASS_Ticker_Info>();
            CLASS_Ticker_Info        OBJECT_Actual_Ticker = new CLASS_Ticker_Info();

            Yahoo.IgnoreEmptyRows = true;

            IReadOnlyDictionary <string, Security> Securities = await Yahoo.Symbols(ARRAY_Input_Tickers).Fields(Field.Symbol, Field.RegularMarketPrice, Field.RegularMarketDayLow, Field.RegularMarketOpen, Field.RegularMarketDayHigh).QueryAsync();

            for (int i = 0; i <= ARRAY_Input_Tickers.Length - 1; i++)
            {
                try
                {
                    OBJECT_Actual_Ticker        = new CLASS_Ticker_Info();
                    OBJECT_Actual_Ticker.Ticker = ARRAY_Input_Tickers[i];
                    try { OBJECT_Actual_Ticker.Open = Securities[ARRAY_Input_Tickers[i]][Field.RegularMarketOpen]; } catch { }
                    try { OBJECT_Actual_Ticker.Current = Securities[ARRAY_Input_Tickers[i]][Field.RegularMarketPrice]; } catch { }
                    try { OBJECT_Actual_Ticker.High = Securities[ARRAY_Input_Tickers[i]][Field.RegularMarketDayHigh]; } catch { }
                    try { OBJECT_Actual_Ticker.Low = Securities[ARRAY_Input_Tickers[i]][Field.RegularMarketDayLow]; } catch { }
                    LIST_Tickers.Add(OBJECT_Actual_Ticker);
                }
                catch { }
            }

            return(LIST_Tickers);
        }
        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);
        }
        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);
        }
Ejemplo n.º 22
0
 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}");
     }
 }
Ejemplo n.º 23
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);
            }
        }
Ejemplo n.º 24
0
        public void Yahoo()
        {
            Yahoo yahoo = new Yahoo(driver);

            yahoo.GoToSite();
            yahoo.SendWord();
            yahoo.HeadersToListAllPages();
        }
Ejemplo n.º 25
0
        private static async Task callYahoo(string stockCode)
        {
            var securities = await Yahoo.Symbols(stockCode).Fields(Field.Symbol, Field.RegularMarketPrice).QueryAsync();

            var stk = securities[stockCode];

            sValue = Convert.ToString(stk.RegularMarketPrice);
        }
Ejemplo n.º 26
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);
        }
Ejemplo n.º 27
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());
        }
Ejemplo n.º 28
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]);
                }
            }
        }
Ejemplo n.º 29
0
        public static async Task <Security> GetQuoteAsync(string symbol)
        {
            // You could query multiple symbols with multiple fields through the following steps:
            var securities = await Yahoo.Symbols(symbol).QueryAsync();

            var quote = securities[symbol];

            return(quote);
        }
Ejemplo n.º 30
0
        public async Task <object> GetStockDetails(string symbol)
        {
            symbol = symbol.ToUpper();
            var result = await Yahoo.Symbols(symbol)
                         .Fields(Enum.GetValues <Field>())
                         .QueryAsync();

            return(result[symbol].Fields);
        }
 /// <summary>
 /// Initializes a new instance of the AuthenticationException class with the specified error message, nested exception and error code.
 /// </summary>
 /// <param name="message">The text of the error message.</param>
 /// <param name="innerException">A nested exception.</param>
 /// <param name="errorCode">The <see cref="Yahoo.AuthenticationErrorCode">AuthenticationErrorCode</see>.</param>
 public AuthenticationException(string message, Exception innerException, Yahoo.AuthenticationErrorCode errorCode)
     : base(message, innerException)
 {
     _errorCode = errorCode;
 }