static void Main(string[] args) { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); WebClient myWebClient = new WebClient(); var i = 0; Dictionary <string, decimal?> currentStockValue = new Dictionary <string, decimal?>(); Dictionary <string, decimal?> stocksAndTheirHighAvgd = new Dictionary <string, decimal?>(); Dictionary <string, decimal?> stocksAndTheirLowAvgd = new Dictionary <string, decimal?>(); Dictionary <string, List <NSE.StockData> > last12DaysStockData = new Dictionary <string, List <NSE.StockData> >(); Dictionary <string, int> hasDailyStdDevBeenHigherThan30percentAvgStdDevDays = new Dictionary <string, int>(); myWebClient.DownloadFile("https://archives.nseindia.com/content/equities/Companies_proposed_to_be_delisted.xlsx", @"C:\Trading\BhavCopy\Last50DaysNSE\ToBeDelistedStockSymbols.xlsx"); myWebClient.DownloadFile("https://archives.nseindia.com/content/equities/delisted.xlsx", @"C:\Trading\BhavCopy\Last50DaysNSE\DelistedStockSymbols.xlsx"); List <string> delistedStockSymbols = new EpPlusHelper().ReadFromExcel <List <NSE.DelistedStockData> >(@"C:\Trading\BhavCopy\Last50DaysNSE\DelistedStockSymbols.xlsx", "delisted").Select(x => x.Symbol).ToList(); List <string> toBeDelistedStockSymbols = new EpPlusHelper().ReadFromExcel <List <NSE.ToBeDelistedStockData> >(@"C:\Trading\BhavCopy\Last50DaysNSE\ToBeDelistedStockSymbols.xlsx", "Sheet1").Select(x => x.Symbol).ToList(); foreach (int item in Enumerable.Range(0, 12).ToList()) { var consideredDate = DateTime.Now.Date.AddDays(-item); if (consideredDate.DayOfWeek != DayOfWeek.Saturday && consideredDate.DayOfWeek != DayOfWeek.Sunday) { var dateString = consideredDate.ToString("dd-MM-yy").Split("-"); var stringKey = dateString[0] + dateString[1] + dateString[2]; // Date against which we are interetsed to get the records. var url = "https://www1.nseindia.com/archives/equities/bhavcopy/pr/PR" + stringKey + ".zip"; // NSE Data for a given day. try { var downloadFilePath = @"C:\Trading\BhavCopy\Last50DaysNSE\" + stringKey + ".zip"; var extractPath = @"C:\Trading\BhavCopy\NSEResponse"; myWebClient.DownloadFile(url, downloadFilePath); try { Directory.Delete(extractPath, true); } catch { } // Clearing out NSEResponse folder after every day's stockData is added up System.IO.Compression.ZipFile.ExtractToDirectory(downloadFilePath, extractPath, true); CreatexlsxFile(extractPath, stringKey); // Moving CSV File contents to XLSX format as EPPlus can only read xlsx formatted data. List <NSE.StockData> stockData = new EpPlusHelper().ReadFromExcel <List <NSE.StockData> >(extractPath + @"\Pd" + stringKey + ".xlsx", "Pd" + stringKey); var delistFilteredEquityStockData = stockData.Where(x => x.SERIES == "EQ" && !delistedStockSymbols.Contains(x.SYMBOL) && !toBeDelistedStockSymbols.Contains(x.SYMBOL)).ToList(); // Here, we get stocks which arent delisted or on the delistable notice list. last12DaysStockData.Add(stringKey, delistFilteredEquityStockData); var keyValues = delistFilteredEquityStockData.Select(x => new { Symbol = x.SYMBOL, CurrentPrice = x.CLOSE_PRICE }); foreach (var keyValue in keyValues.Where(x => !currentStockValue.ContainsKey(x.Symbol))) { decimal.TryParse(keyValue.CurrentPrice, out decimal currentPrice); currentStockValue.Add(keyValue.Symbol, currentPrice); } } catch (Exception ex) { continue; } } } Dictionary <string, decimal?>[] dailyStdDeviationAvgd = new Dictionary <string, decimal?> [last12DaysStockData.Values.Count]; foreach (var item in last12DaysStockData) { foreach (var stock in item.Value.Where(x => x.SYMBOL != null && x.OPEN_PRICE != null && x.PREV_CL_PR != null)) { var validHighPrice = decimal.TryParse(stock.HIGH_PRICE, out decimal highPrice); var validLowPrice = decimal.TryParse(stock.LOW_PRICE, out decimal lowPrice); if (validHighPrice && validLowPrice) // If Open & PreClose prices are not null in excel sheet { var priceDifference = highPrice - lowPrice; if (!stocksAndTheirHighAvgd.ContainsKey(stock.SYMBOL)) { stocksAndTheirHighAvgd.Add(stock.SYMBOL, highPrice); } else { stocksAndTheirHighAvgd[stock.SYMBOL] += highPrice; } if (!stocksAndTheirLowAvgd.ContainsKey(stock.SYMBOL)) { stocksAndTheirLowAvgd.Add(stock.SYMBOL, lowPrice); } else { stocksAndTheirLowAvgd[stock.SYMBOL] += lowPrice; } // Storing the Difference of High - Low. Close for each day (denoted by i) and for each stock symbol into : diffOfOpenPrevCloseForEachStock if (dailyStdDeviationAvgd[i] == null) { dailyStdDeviationAvgd[i] = new Dictionary <string, decimal?> { { stock.SYMBOL, priceDifference } } } ; else { dailyStdDeviationAvgd[i].Add(stock.SYMBOL, priceDifference); } } } i++; } i = 0; Dictionary <string, decimal?> eachStockStdDevAverageOver12Days = new Dictionary <string, decimal?>(); List <string> stockNames = new List <string>(); Dictionary <string, int> counterOfIthStock = new Dictionary <string, int>(); foreach (var item in last12DaysStockData) { foreach (var stock in item.Value.Where(x => x.SYMBOL != null)) { dailyStdDeviationAvgd[i].TryGetValue(stock.SYMBOL, out decimal? stdDeviation); if (stdDeviation != null) { if (!stockNames.Contains(stock.SYMBOL)) { stockNames.Add(stock.SYMBOL); } if (!counterOfIthStock.ContainsKey(stock.SYMBOL)) { counterOfIthStock.Add(stock.SYMBOL, 1); // get total count to use later for diving total calculated in line 113 } else { counterOfIthStock[stock.SYMBOL] += 1; } if (!eachStockStdDevAverageOver12Days.ContainsKey(stock.SYMBOL)) { eachStockStdDevAverageOver12Days.Add(stock.SYMBOL, stdDeviation); } else { eachStockStdDevAverageOver12Days[stock.SYMBOL] += stdDeviation; // eachStockAverageOver50Days , currently add all values and save total } } } i++; } foreach (var name in stockNames.Distinct().Where(x => eachStockStdDevAverageOver12Days.ContainsKey(x) && counterOfIthStock.ContainsKey(x))) { try { eachStockStdDevAverageOver12Days[name] = ((decimal)eachStockStdDevAverageOver12Days[name] / (decimal)counterOfIthStock[name]); } catch { } // find average used in line 113 and line 106 try { stocksAndTheirLowAvgd[name] = ((decimal)stocksAndTheirLowAvgd[name] / (decimal)counterOfIthStock[name]); } catch { } try { stocksAndTheirHighAvgd[name] = ((decimal)stocksAndTheirHighAvgd[name] / (decimal)counterOfIthStock[name]); } catch { } } i = 0; foreach (var item in last12DaysStockData) { foreach (var stock in item.Value.Where(x => x.SYMBOL != null && x.OPEN_PRICE != null && x.PREV_CL_PR != null)) { var validHighPrice = decimal.TryParse(stock.HIGH_PRICE, out decimal highPrice); var validLowPrice = decimal.TryParse(stock.LOW_PRICE, out decimal lowPrice); if (validHighPrice && validLowPrice) // If Open & PreClose prices are not null in excel sheet { var priceDifference = highPrice - lowPrice; if (priceDifference > 0.98m * dailyStdDeviationAvgd[i][stock.SYMBOL]) { if (!hasDailyStdDevBeenHigherThan30percentAvgStdDevDays.ContainsKey(stock.SYMBOL)) { hasDailyStdDevBeenHigherThan30percentAvgStdDevDays.Add(stock.SYMBOL, 1); } else { hasDailyStdDevBeenHigherThan30percentAvgStdDevDays[stock.SYMBOL] += 1; } } else if (!hasDailyStdDevBeenHigherThan30percentAvgStdDevDays.ContainsKey(stock.SYMBOL)) { hasDailyStdDevBeenHigherThan30percentAvgStdDevDays.Add(stock.SYMBOL, 0); } } } i++; } var numbers = new List <string>(); foreach (var num in Enumerable.Range(0, 9).ToArray()) { numbers.Add("'" + num + "'"); } var screenedAvgStdDevStocks = eachStockStdDevAverageOver12Days.Where(x => currentStockValue.ContainsKey(x.Key) && x.Value >= (currentStockValue[x.Key] * 0.07m)); var screenedStocks = from avgStdDev in screenedAvgStdDevStocks join lowPrice in stocksAndTheirLowAvgd on avgStdDev.Key equals lowPrice.Key join highPrice in stocksAndTheirHighAvgd on avgStdDev.Key equals highPrice.Key join positive40PercentileStdDevDay in hasDailyStdDevBeenHigherThan30percentAvgStdDevDays on avgStdDev.Key equals positive40PercentileStdDevDay.Key where currentStockValue[avgStdDev.Key] < (1.05m * lowPrice.Value) && (avgStdDev.Value >= 5) && (((decimal?)positive40PercentileStdDevDay.Value) / ((decimal)last12DaysStockData.Count)) > 0.93m // && currentStockValue[avgStdDev.Key] < ((lowPrice.Value + highPrice.Value) /2) select new { Stock = highPrice.Key, AverageStdDev = avgStdDev.Value, CurrentStockPrice = currentStockValue[avgStdDev.Key], StdDevToCurrentValueRatio = (avgStdDev.Value / currentStockValue[avgStdDev.Key]) * 100, StdDeviationMorethan90thPercentileOfAvgStdDevDays = hasDailyStdDevBeenHigherThan30percentAvgStdDevDays[avgStdDev.Key], PricePositiveByTotalDays = (((decimal?)hasDailyStdDevBeenHigherThan30percentAvgStdDevDays[avgStdDev.Key]) / ((decimal)last12DaysStockData.Count)) }; screenedStocks = screenedStocks.OrderByDescending(x => x.StdDevToCurrentValueRatio); string json = JsonConvert.SerializeObject(screenedStocks, Formatting.Indented); Console.WriteLine(json); Console.ReadLine(); }
static void Main(string[] args) { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); WebClient myWebClient = new WebClient(); var i = 0; var path = @"C:\Trading\BhavCopy\Rachana\EVEBITDA"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } myWebClient.DownloadFile("https://archives.nseindia.com/content/equities/Companies_proposed_to_be_delisted.xlsx", @"C:\Trading\BhavCopy\Rachana\EVEBITDA\ToBeDelistedStockSymbols.xlsx"); myWebClient.DownloadFile("https://archives.nseindia.com/content/equities/delisted.xlsx", @"C:\Trading\BhavCopy\Rachana\EVEBITDA\DelistedStockSymbols.xlsx"); List <string> delistedStockSymbols = new EpPlusHelper().ReadFromExcel <List <NSE.DelistedStockData> >(@"C:\Trading\BhavCopy\Rachana\EVEBITDA\DelistedStockSymbols.xlsx", "delisted").Select(x => x.Symbol).ToList(); List <string> toBeDelistedStockSymbols = new EpPlusHelper().ReadFromExcel <List <NSE.ToBeDelistedStockData> >(@"C:\Trading\BhavCopy\Rachana\EVEBITDA\ToBeDelistedStockSymbols.xlsx", "Sheet1").Select(x => x.Symbol).ToList(); Dictionary <string, List <NSE.StockData> > last100DaysStockData = new Dictionary <string, List <NSE.StockData> >(); Dictionary <string, List <McapData> > last100DaysMcapData = new Dictionary <string, List <McapData> >(); List <McapData> MCapData = new List <McapData>(); foreach (int item in Enumerable.Range(0, 100).ToList()) { var dateConsidered = DateTime.Now.Date.AddDays(-item); if (dateConsidered.DayOfWeek != DayOfWeek.Saturday && dateConsidered.DayOfWeek != DayOfWeek.Sunday) { var dateString = dateConsidered.ToString("dd-MM-yy").Split("-"); var stringKey = dateString[0] + dateString[1] + dateString[2]; // Date agianst which we are interetsed to get the records. var url = "https://www1.nseindia.com/archives/equities/bhavcopy/pr/PR" + stringKey + ".zip"; // NSE Data for a given day. try { var downloadFilePath = @"C:\Trading\BhavCopy\Last50DaysNSE\" + stringKey + ".zip"; var extractPath = @"C:\Trading\BhavCopy\NSEResponse"; myWebClient.DownloadFile(url, downloadFilePath); try { Directory.Delete(extractPath, true); } catch { } // Clearing out NSEResponse folder after every day's stockData is added up System.IO.Compression.ZipFile.ExtractToDirectory(downloadFilePath, extractPath, true); CreateXlsxFile(extractPath, stringKey); // Moving CSV File contents to XLSX format as EPPlus can only read xlsx formatted data. List <NSE.StockData> stockData = new EpPlusHelper().ReadFromExcel <List <NSE.StockData> >(extractPath + @"\Pd" + stringKey + ".xlsx", "Pd" + stringKey); var delistFilteredEquityStockData = stockData.Where(x => x.SERIES == "EQ" && !delistedStockSymbols.Contains(x.SYMBOL) && !toBeDelistedStockSymbols.Contains(x.SYMBOL)).ToList(); // Here, we get stocks which arent delisted or on the delistable notice list. last100DaysStockData.Add(stringKey, delistFilteredEquityStockData); } catch (Exception ex) { continue; } } } var consideredDate = DateTime.Now.Date.AddDays(-1); if (consideredDate.DayOfWeek != DayOfWeek.Saturday && consideredDate.DayOfWeek != DayOfWeek.Sunday) { var dateString = consideredDate.ToString("dd-MM-yy").Split("-"); var stringKey = dateString[0] + dateString[1] + dateString[2]; // Date against which we are interested to get records. var url = "https://www1.nseindia.com/archives/equities/bhavcopy/pr/PR" + stringKey + ".zip"; // NSE Data for a given day. int counter = 0; try { var downloadFilePath = @"C:\Trading\BhavCopy\Last50DaysNSE\" + stringKey + ".zip"; var extractPath = @"C:\Trading\BhavCopy\NSEResponse"; myWebClient.DownloadFile(url, downloadFilePath); try { Directory.Delete(extractPath, true); } catch { } // Clearing out NSEResponse folder after every day's stockData is added up System.IO.Compression.ZipFile.ExtractToDirectory(downloadFilePath, extractPath, true); CreateXlsxFile(extractPath, stringKey); // Moving CSV File contents to XLSX format as EPPlus can only read xlsx formatted data. List <NSE.StockData> stockData = new EpPlusHelper().ReadFromExcel <List <NSE.StockData> >(extractPath + @"\Pd" + stringKey + ".xlsx", "Pd" + stringKey); var delistFilteredEquityStockData = stockData.Where(x => x.SERIES == "EQ" && !delistedStockSymbols.Contains(x.SYMBOL) && !toBeDelistedStockSymbols.Contains(x.SYMBOL)).ToList(); // Here, we get stocks which arent delisted or on the delistable notice list. foreach (var delistFilteredStock in delistFilteredEquityStockData) { string urlAddress = "https://www.google.com/search?q=https://www.moneycontrol.com/stocks/company_info/stock_news.php+" + delistFilteredStock.SYMBOL + "&oq=https://www.moneycontrol.com/stocks/company_info/stock_news.php+" + delistFilteredStock.SYMBOL; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress); request.Headers.Add("User-Agent", @"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5)\AppleWebKit / 537.36(KHTML, like Gecko) Safari / 537.36"); if (counter % 2 == 0) { Thread.Sleep(15000); } counter++; try { HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { Stream receiveStream = response.GetResponseStream(); StreamReader readStream = string.IsNullOrWhiteSpace(response.CharacterSet) ? new StreamReader(receiveStream) : new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet)); string data = readStream.ReadToEnd(); var moneyControlSymbolCode = data.Split("https://www.moneycontrol.com/stocks/company_info/stock_news.php%3Fsc_id%3D")[1].Split("%")[0]; //moneyControlApiUrlForMCap += moneyControlSymbolCode + "%2C"; response.Close(); readStream.Close(); var moneyControlApiUrlForMCap = "https://api.moneycontrol.com/mcapi/v1/stock/get-stock-price?scIdList=" + moneyControlSymbolCode + "&scId=" + moneyControlSymbolCode; using var client = new HttpClient(); string content = ""; client.BaseAddress = new Uri("https://api.moneycontrol.com"); moneyControlApiUrlForMCap = moneyControlApiUrlForMCap.Split("https://api.moneycontrol.com")[1]; client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage moneyControlApiResponse = client.GetAsync(moneyControlApiUrlForMCap).GetAwaiter().GetResult(); if (moneyControlApiResponse.IsSuccessStatusCode) { content = moneyControlApiResponse.Content.ReadAsStringAsync().GetAwaiter().GetResult(); var deserialisedContent = JsonConvert.DeserializeObject <WrappingMcapData>(content); var singleMCapData = deserialisedContent.Data.First(); singleMCapData.Symbol = delistFilteredStock.SYMBOL; singleMCapData.NoOfShares = (long)((decimal)singleMCapData.MarketCap / (decimal)singleMCapData.LastPrice); MCapData.Add(singleMCapData); // Data for Xth day completely with all symbols. } } } catch (Exception e2) { } } last100DaysMcapData.Add(stringKey, MCapData); //last100DaysStockData.Add(stringKey, delistFilteredEquityStockData); } catch (Exception ex) { } } Dictionary <string, int> exponentialFactorPerStock = new Dictionary <string, int>(); Dictionary <string, int> denominatorCountAggregateForVwapCalculationPerStock = new Dictionary <string, int>(); Dictionary <string, decimal> exponentialVwapAggregateForDayPerStock = new Dictionary <string, decimal>(); foreach (var item in last100DaysStockData) { foreach (var stock in item.Value.Where(x => x.SYMBOL != null && x.NET_TRDQTY != null && x.NET_TRDQTY != "0" && x.NET_TRDVAL != null && x.NET_TRDVAL != "0")) { var isValidTradedQuantity = decimal.TryParse(stock.NET_TRDQTY, out decimal tradedQuantityForDay); var isValidTradedValue = decimal.TryParse(stock.NET_TRDVAL, out decimal tradedValueForDay); if (isValidTradedQuantity && isValidTradedValue) // If Open & PreClose prices are not null in excel sheet { if (!exponentialFactorPerStock.ContainsKey(stock.SYMBOL)) { exponentialFactorPerStock.Add(stock.SYMBOL, 100); } else { exponentialFactorPerStock[stock.SYMBOL] -= 1; } decimal vwapForDay = tradedValueForDay / tradedQuantityForDay; if (!exponentialVwapAggregateForDayPerStock.ContainsKey(stock.SYMBOL)) { exponentialVwapAggregateForDayPerStock.Add(stock.SYMBOL, vwapForDay * exponentialFactorPerStock[stock.SYMBOL]); } else { exponentialVwapAggregateForDayPerStock[stock.SYMBOL] += vwapForDay * exponentialFactorPerStock[stock.SYMBOL]; } if (!denominatorCountAggregateForVwapCalculationPerStock.ContainsKey(stock.SYMBOL)) { denominatorCountAggregateForVwapCalculationPerStock.Add(stock.SYMBOL, exponentialFactorPerStock[stock.SYMBOL]); } else { denominatorCountAggregateForVwapCalculationPerStock[stock.SYMBOL] += exponentialFactorPerStock[stock.SYMBOL]; } } } i++; } Dictionary <string, decimal> exponentialVwapPerStock = new Dictionary <string, decimal>(); Dictionary <string, decimal> lastClosePriceOfStocks = new Dictionary <string, decimal>(); Dictionary <string, decimal> vwapGreaterThan20PercentClosePriceStocks = new Dictionary <string, decimal>(); foreach (var symbol in exponentialFactorPerStock.Keys) { decimal exponentialVwapForSymbol = exponentialVwapAggregateForDayPerStock[symbol] / denominatorCountAggregateForVwapCalculationPerStock[symbol]; exponentialVwapPerStock.Add(symbol, exponentialVwapForSymbol); if (!last100DaysStockData.First().Value.Exists(x => x.SYMBOL == symbol)) { continue; } var IslastClosePriceValid = decimal.TryParse(last100DaysStockData.First().Value.Find(x => x.SYMBOL == symbol).CLOSE_PRICE, out decimal lastClosePrice); if (IslastClosePriceValid) { lastClosePriceOfStocks.Add(symbol, lastClosePrice); if (exponentialVwapPerStock[symbol] >= 1.2m * lastClosePriceOfStocks[symbol]) { vwapGreaterThan20PercentClosePriceStocks.Add(symbol, exponentialVwapPerStock[symbol]); } } } string json = JsonConvert.SerializeObject(vwapGreaterThan20PercentClosePriceStocks, Formatting.Indented); Console.WriteLine(json); Console.ReadLine(); }
static void Main(string[] args) { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); WebClient myWebClient = new WebClient(); var i = 0; Dictionary <string, decimal?> stocksAndTheirOpenPrice = new Dictionary <string, decimal?>(); Dictionary <string, List <NSE.StockData> > last50DaysStockData = new Dictionary <string, List <NSE.StockData> >(); Dictionary <string, int> hasBeenPositiveFor = new Dictionary <string, int>(); Dictionary <string, int> hasBeenNegativeFor = new Dictionary <string, int>(); Dictionary <string, int> hasBeenZeroDiffFor = new Dictionary <string, int>(); myWebClient.DownloadFile("https://archives.nseindia.com/content/equities/Companies_proposed_to_be_delisted.xlsx", @"C:\Trading\BhavCopy\Last50DaysNSE\ToBeDelistedStockSymbols.xlsx"); myWebClient.DownloadFile("https://archives.nseindia.com/content/equities/delisted.xlsx", @"C:\Trading\BhavCopy\Last50DaysNSE\DelistedStockSymbols.xlsx"); List <string> delistedStockSymbols = new EpPlusHelper().ReadFromExcel <List <NSE.DelistedStockData> >(@"C:\Trading\BhavCopy\Last50DaysNSE\DelistedStockSymbols.xlsx", "delisted").Select(x => x.Symbol).ToList(); List <string> toBeDelistedStockSymbols = new EpPlusHelper().ReadFromExcel <List <NSE.ToBeDelistedStockData> >(@"C:\Trading\BhavCopy\Last50DaysNSE\ToBeDelistedStockSymbols.xlsx", "Sheet1").Select(x => x.Symbol).ToList(); foreach (int item in Enumerable.Range(0, 50).ToList()) { var consideredDate = DateTime.Now.Date.AddDays(-item); if (consideredDate.DayOfWeek != DayOfWeek.Saturday && consideredDate.DayOfWeek != DayOfWeek.Sunday) { var dateString = consideredDate.ToString("dd-MM-yy").Split("-"); var stringKey = dateString[0] + dateString[1] + dateString[2]; // Date agianst which we are interetsed to get the records. var url = "https://www1.nseindia.com/archives/equities/bhavcopy/pr/PR" + stringKey + ".zip"; // NSE Data for a given day. try { var downloadFilePath = @"C:\Trading\BhavCopy\Last50DaysNSE\" + stringKey + ".zip"; var extractPath = @"C:\Trading\BhavCopy\NSEResponse"; myWebClient.DownloadFile(url, downloadFilePath); try { Directory.Delete(extractPath, true); } catch { } // Clearing out NSEResponse folder after every day's stockData is added up System.IO.Compression.ZipFile.ExtractToDirectory(downloadFilePath, extractPath, true); CreateXlsxFile(extractPath, stringKey); // Moving CSV File contents to XLSX format as EPPlus can only read xlsx formatted data. List <NSE.StockData> stockData = new EpPlusHelper().ReadFromExcel <List <NSE.StockData> >(extractPath + @"\Pd" + stringKey + ".xlsx", "Pd" + stringKey); var delistFilteredEquityStockData = stockData.Where(x => x.SERIES == "EQ" && !delistedStockSymbols.Contains(x.SYMBOL) && !toBeDelistedStockSymbols.Contains(x.SYMBOL)).ToList(); // Here, we get stocks which arent delisted or on the delistable notice list. last50DaysStockData.Add(stringKey, delistFilteredEquityStockData); } catch (Exception ex) { continue; } } } Dictionary <string, decimal?>[] diffOfOpenPrevCloseForEachStock = new Dictionary <string, decimal?> [last50DaysStockData.Values.Count]; foreach (var item in last50DaysStockData) { foreach (var stock in item.Value.Where(x => x.SYMBOL != null && x.OPEN_PRICE != null && x.PREV_CL_PR != null)) { var validOpenPrice = decimal.TryParse(stock.OPEN_PRICE, out decimal openPrice); var validPrevClosePrice = decimal.TryParse(stock.PREV_CL_PR, out decimal prevClosePrice); if (validOpenPrice && validPrevClosePrice) // If Open & PreClose prices are not null in excel sheet { var priceDifference = openPrice - prevClosePrice; if (!stocksAndTheirOpenPrice.ContainsKey(stock.SYMBOL)) { stocksAndTheirOpenPrice.Add(stock.SYMBOL, openPrice); } //Below section is to check how consistently the price has been positive wrt (Open-Prev Close) if (priceDifference > 0 && !hasBeenPositiveFor.ContainsKey(stock.SYMBOL)) { hasBeenPositiveFor.Add(stock.SYMBOL, 1); // Has (Open-PrevClose) as +ve for these many days. } else if (priceDifference > 0) { hasBeenPositiveFor[stock.SYMBOL] += 1; } else if (priceDifference < 0 && !hasBeenNegativeFor.ContainsKey(stock.SYMBOL)) { hasBeenNegativeFor.Add(stock.SYMBOL, 1); } else if (priceDifference < 0) { hasBeenNegativeFor[stock.SYMBOL] += 1; } else if (!hasBeenZeroDiffFor.ContainsKey(stock.SYMBOL)) { hasBeenZeroDiffFor.Add(stock.SYMBOL, 1); } else { hasBeenZeroDiffFor[stock.SYMBOL]++; // Open - PrevClose = 0 for these many days. } // Storing the Difference of Open - Prev. Close for each day (denoted by i) and for each stock symbol into : diffOfOpenPrevCloseForEachStock if (diffOfOpenPrevCloseForEachStock[i] == null) { diffOfOpenPrevCloseForEachStock[i] = new Dictionary <string, decimal?> { { stock.SYMBOL, priceDifference } } } ; else { diffOfOpenPrevCloseForEachStock[i].Add(stock.SYMBOL, priceDifference); } } } i++; } i = 0; Dictionary <string, decimal?> eachStockAverageOver50Days = new Dictionary <string, decimal?>(); List <string> stockNames = new List <string>(); Dictionary <string, int> counterOfIthStock = new Dictionary <string, int>(); foreach (var item in last50DaysStockData) { foreach (var stock in item.Value.Where(x => x.SYMBOL != null)) { var isAveragePresent = diffOfOpenPrevCloseForEachStock[i].TryGetValue(stock.SYMBOL, out decimal? openCloseDiff); // Against each day sugested by i, check if this particular stock's value exists. if (isAveragePresent && openCloseDiff != null) { if (!stockNames.Contains(stock.SYMBOL)) { stockNames.Add(stock.SYMBOL); } if (!counterOfIthStock.ContainsKey(stock.SYMBOL)) { counterOfIthStock.Add(stock.SYMBOL, 1); // get total count to use later for diving total calculated in line 113 } else { counterOfIthStock[stock.SYMBOL] += 1; } if (!eachStockAverageOver50Days.ContainsKey(stock.SYMBOL)) { eachStockAverageOver50Days.Add(stock.SYMBOL, openCloseDiff); } else { eachStockAverageOver50Days[stock.SYMBOL] += openCloseDiff; // eachStockAverageOver50Days , currently add all values and save total } } } i++; } foreach (var name in stockNames.Where(x => eachStockAverageOver50Days.ContainsKey(x) && counterOfIthStock.ContainsKey(x))) { eachStockAverageOver50Days[name] = eachStockAverageOver50Days[name] / counterOfIthStock[name]; // find average used in line 113 and line 106 } var numbers = new List <string>(); foreach (var num in Enumerable.Range(0, 9).ToArray()) { numbers.Add("'" + num + "'"); } var screenedAvgOpenCloseStocks = eachStockAverageOver50Days.Where(x => stocksAndTheirOpenPrice[x.Key] != null && x.Value >= (stocksAndTheirOpenPrice[x.Key] * 0.02m)); // (> 2% of the stock's value happens to be the open prevClose difference on an average) // && stocksAndTheirOpenPrice[x.Key] > 100 && stocksAndTheirOpenPrice[x.Key] < 10000 var screenedStocks = from avgOpenClose in screenedAvgOpenCloseStocks join OpenPrice in stocksAndTheirOpenPrice on avgOpenClose.Key equals OpenPrice.Key where OpenPrice.Value != avgOpenClose.Value && hasBeenPositiveFor.ContainsKey(OpenPrice.Key) && (((decimal?)hasBeenPositiveFor[OpenPrice.Key] / ((decimal)last50DaysStockData.Count)) > 0.8m)// Has yielded positive outcomes for more than 80% of the time on an average && !numbers.Contains(avgOpenPriceClose.Key.Substring(0, 1)) // && OpenPrice.Value > 160 && OpenPrice.Value < 25000 // && avgOpenPriceClose.Value < (.07m * OpenPrice.Value) // To remove fake ones which show prices for one day only and inactive on other days select new { PricePositiveForDays = hasBeenPositiveFor[OpenPrice.Key], PricePositiveByTotalDays = (((decimal?)hasBeenPositiveFor[OpenPrice.Key]) / ((decimal)last50DaysStockData.Count)), Stock = avgOpenClose.Key, AverageOpenCloseDiff = avgOpenClose.Value, OpenPrice50DaysAgo = OpenPrice.Value, OpenCloseDiffToOpenRatio = (avgOpenClose.Value / OpenPrice.Value) * 100 }; string json = JsonConvert.SerializeObject(screenedStocks, Formatting.Indented); Console.WriteLine(json); Console.ReadLine(); }
static void Main(string[] args) { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); WebClient myWebClient = new WebClient(); List <DividendData> delistFilteredEquityBuybackData = new List <DividendData>(); List <DividendData> bonusUpcomingStockData = new List <DividendData>(); Dictionary <string, decimal?> currentStockValue = new Dictionary <string, decimal?>(); Dictionary <string, decimal?> stocksAndTheirHighAvgd = new Dictionary <string, decimal?>(); Dictionary <string, decimal?> stocksAndTheirLowAvgd = new Dictionary <string, decimal?>(); Dictionary <string, List <DividendData> > last20YearsStockData = new Dictionary <string, List <DividendData> >(); Dictionary <string, List <DividendDataOutput> > symbolWiseBonuses = new Dictionary <string, List <DividendDataOutput> >(); Dictionary <string, int> hasDailyStdDevBeenHigherThan30percentAvgStdDevDays = new Dictionary <string, int>(); myWebClient.DownloadFile("https://archives.nseindia.com/content/equities/Companies_proposed_to_be_delisted.xlsx", @"C:\Trading\BhavCopy\Last50DaysNSE\ToBeDelistedStockSymbols.xlsx"); myWebClient.DownloadFile("https://archives.nseindia.com/content/equities/delisted.xlsx", @"C:\Trading\BhavCopy\Last50DaysNSE\DelistedStockSymbols.xlsx"); List <string> delistedStockSymbols = new EpPlusHelper().ReadFromExcel <List <DelistedStockData> >(@"C:\Trading\BhavCopy\Last50DaysNSE\DelistedStockSymbols.xlsx", "delisted").Select(x => x.Symbol).ToList(); List <string> toBeDelistedStockSymbols = new EpPlusHelper().ReadFromExcel <List <ToBeDelistedStockData> >(@"C:\Trading\BhavCopy\Last50DaysNSE\ToBeDelistedStockSymbols.xlsx", "Sheet1").Select(x => x.Symbol).ToList(); var stocksWhichHaveBeenAnnounced = new List <DividendData>(); var consideredDate = DateTime.Now.Date.AddDays(-1); while (consideredDate.DayOfWeek == DayOfWeek.Saturday || consideredDate.DayOfWeek == DayOfWeek.Sunday) { consideredDate = consideredDate.AddDays(-1); } var tempDt = consideredDate.ToString("dd-MM-yy").Split("-"); var stringKey = tempDt[0] + tempDt[1] + tempDt[2]; try { var downloadFilePath = @"C:\Trading\BhavCopy\Last10Year\" + stringKey + ".zip"; var extractPath = @"C:\Trading\BhavCopy\NSEBonus"; myWebClient.DownloadFile("https://www1.nseindia.com/archives/equities/bhavcopy/pr/PR" + stringKey + ".zip", downloadFilePath); try { Directory.Delete(extractPath, true); } catch { } System.IO.Compression.ZipFile.ExtractToDirectory(downloadFilePath, extractPath, true); CreateBcXlsxFile(extractPath, stringKey); List <DividendData> bonusAndDividendData = new EpPlusHelper().ReadFromExcel <List <DividendData> >(extractPath + @"\Bc" + stringKey + ".xlsx", "Bc" + stringKey); delistFilteredEquityBuybackData = bonusAndDividendData.Where(x => x.PURPOSE != null && x.PURPOSE.Contains("BUYBACK") && x.SERIES != null && x.SERIES == "EQ" && x.SYMBOL != null && !delistedStockSymbols.Contains(x.SYMBOL) && !toBeDelistedStockSymbols.Contains(x.SYMBOL)).ToList(); DateTime result; foreach (var buyBackData in delistFilteredEquityBuybackData) { bool IsYearDateFormatForRecordDate = DateTime.TryParseExact(buyBackData.EX_DT, "yyyy-dd-MM", CultureInfo.InvariantCulture, DateTimeStyles.None, out result); if (!IsYearDateFormatForRecordDate) { DateTime.TryParseExact(buyBackData.EX_DT, "dd-MM-yy", CultureInfo.InvariantCulture, DateTimeStyles.None, out result); } if (result > DateTime.Today.AddDays(2)) { bonusUpcomingStockData.Add(new DividendData { SYMBOL = buyBackData.SYMBOL, EX_DT = buyBackData.EX_DT, PURPOSE = buyBackData.PURPOSE }); } } stocksWhichHaveBeenAnnounced.AddRange(bonusUpcomingStockData); } catch (Exception ex) { } string json = JsonConvert.SerializeObject(delistFilteredEquityBuybackData, Formatting.Indented); Console.WriteLine("Historical Share Bonus Data: -----\n" + json + "\n-------------\n"); string upcomingGenuineStockBonuses = JsonConvert.SerializeObject(bonusUpcomingStockData, Formatting.Indented); Console.WriteLine("Upcoming Genuine Stock Bonus Data: -----\n" + upcomingGenuineStockBonuses + "\n-------------\n"); Console.ReadLine(); }
static void Main(string[] args) { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); WebClient myWebClient = new WebClient(); Dictionary <string, decimal?> currentStockValue = new Dictionary <string, decimal?>(); Dictionary <string, decimal?> stocksAndTheirHighAvgd = new Dictionary <string, decimal?>(); Dictionary <string, decimal?> stocksAndTheirLowAvgd = new Dictionary <string, decimal?>(); Dictionary <string, List <BonusData> > last20YearsStockData = new Dictionary <string, List <BonusData> >(); Dictionary <string, List <BonusDataOutput> > symbolWiseBonuses = new Dictionary <string, List <BonusDataOutput> >(); Dictionary <string, int> hasDailyStdDevBeenHigherThan30percentAvgStdDevDays = new Dictionary <string, int>(); myWebClient.DownloadFile("https://archives.nseindia.com/content/equities/Companies_proposed_to_be_delisted.xlsx", @"C:\Trading\BhavCopy\Last50DaysNSE\ToBeDelistedStockSymbols.xlsx"); myWebClient.DownloadFile("https://archives.nseindia.com/content/equities/delisted.xlsx", @"C:\Trading\BhavCopy\Last50DaysNSE\DelistedStockSymbols.xlsx"); List <string> delistedStockSymbols = new EpPlusHelper().ReadFromExcel <List <DelistedStockData> >(@"C:\Trading\BhavCopy\Last50DaysNSE\DelistedStockSymbols.xlsx", "delisted").Select(x => x.Symbol).ToList(); List <string> toBeDelistedStockSymbols = new EpPlusHelper().ReadFromExcel <List <ToBeDelistedStockData> >(@"C:\Trading\BhavCopy\Last50DaysNSE\ToBeDelistedStockSymbols.xlsx", "Sheet1").Select(x => x.Symbol).ToList(); var stocksWhichHaveBeenAnnounced = new List <BonusData>(); var consideredDate = DateTime.Now.Date.AddDays(-1); while (consideredDate.DayOfWeek == DayOfWeek.Saturday || consideredDate.DayOfWeek == DayOfWeek.Sunday) { consideredDate = consideredDate.AddDays(-1); } var tempDt = consideredDate.ToString("dd-MM-yy").Split("-"); var stringKey = tempDt[0] + tempDt[1] + tempDt[2]; try { var downloadFilePath = @"C:\Trading\BhavCopy\Last10Year\" + stringKey + ".zip"; var extractPath = @"C:\Trading\BhavCopy\NSEBonus"; myWebClient.DownloadFile("https://www1.nseindia.com/archives/equities/bhavcopy/pr/PR" + stringKey + ".zip", downloadFilePath); try { Directory.Delete(extractPath, true); } catch { } System.IO.Compression.ZipFile.ExtractToDirectory(downloadFilePath, extractPath, true); CreateBcXlsxFile(extractPath, stringKey); List <BonusData> bonusAndDividendData = new EpPlusHelper().ReadFromExcel <List <BonusData> >(extractPath + @"\Bc" + stringKey + ".xlsx", "Bc" + stringKey); var delistFilteredEquityBonusData = bonusAndDividendData.Where(x => x.PURPOSE != null && x.PURPOSE.Contains("BONUS") && x.SERIES != null && x.SERIES == "EQ" && x.SYMBOL != null && !delistedStockSymbols.Contains(x.SYMBOL) && !toBeDelistedStockSymbols.Contains(x.SYMBOL)).ToList(); foreach (var localBonusData in delistFilteredEquityBonusData) { int[] tempResultArray = new int[2]; int i = 0; foreach (var split in localBonusData.PURPOSE.Split(":")) { tempResultArray[i] = Int32.Parse(Regex.Match(split, @"\d+").Value); i++; } localBonusData.PURPOSE = ((decimal)tempResultArray[0] / (decimal)tempResultArray[1]).ToString(); // Defines the percentage of shares on existing number of shares. } var bonusUpcomingStockData = delistFilteredEquityBonusData.Where(x => DateTime.ParseExact(x.RECORD_DT, "yyyy-dd-MM", CultureInfo.InvariantCulture) > DateTime.Today.AddDays(2)).Select(x => new BonusData { SYMBOL = x.SYMBOL, RECORD_DT = x.RECORD_DT.Replace("/", "-").Trim(), PURPOSE = x.PURPOSE.Trim() }); stocksWhichHaveBeenAnnounced.AddRange(bonusUpcomingStockData); } catch (Exception ex) { } foreach (int month in Enumerable.Range(1, 300).ToList()) { consideredDate = DateTime.Now.Date.AddDays(-1).AddMonths(-month); while (consideredDate.DayOfWeek == DayOfWeek.Saturday || consideredDate.DayOfWeek == DayOfWeek.Sunday) { consideredDate = consideredDate.AddDays(-1); } tempDt = consideredDate.ToString("MM-dd-yy").Split("-"); stringKey = tempDt[1] + tempDt[0] + tempDt[2]; try { var downloadFilePath = @"C:\Trading\BhavCopy\Last10Year\" + stringKey + ".zip"; var extractPath = @"C:\Trading\BhavCopy\NSEBonus"; myWebClient.DownloadFile("https://www1.nseindia.com/archives/equities/bhavcopy/pr/PR" + stringKey + ".zip", downloadFilePath); try { Directory.Delete(extractPath, true); } catch { } System.IO.Compression.ZipFile.ExtractToDirectory(downloadFilePath, extractPath, true); CreateBcXlsxFile(extractPath, stringKey); List <BonusData> bonusAndDividendData = new EpPlusHelper().ReadFromExcel <List <BonusData> >(extractPath + @"\Bc" + stringKey + ".xlsx", "Bc" + stringKey); var delistFilteredEquityBonusData = bonusAndDividendData.Where(x => x.PURPOSE != null && x.PURPOSE.Contains("BONUS") && x.SERIES != null && x.SERIES == "EQ" && x.SYMBOL != null && !delistedStockSymbols.Contains(x.SYMBOL) && !toBeDelistedStockSymbols.Contains(x.SYMBOL)).ToList(); foreach (var localBonusData in delistFilteredEquityBonusData) { int[] tempResultArray = new int[2]; int i = 0; foreach (var split in localBonusData.PURPOSE.Split(":")) { tempResultArray[i] = Int32.Parse(Regex.Match(split, @"\d+").Value); i++; } localBonusData.PURPOSE = ((decimal)tempResultArray[0] / (decimal)tempResultArray[1]).ToString(); // Defines the percentage of shares on existing number of shares. } var bonusStockData = delistFilteredEquityBonusData.Select(x => new BonusData { SYMBOL = x.SYMBOL, RECORD_DT = x.RECORD_DT.Replace("/", "-").Trim(), PURPOSE = x.PURPOSE.Trim() }); last20YearsStockData.Add(stringKey, bonusStockData.ToList()); } catch (Exception ex) { continue; } } Dictionary <string, int> daysForWhichBonusIsStable = new Dictionary <string, int>(); var extractPathForStableDate = @"C:\Trading\BhavCopy\NSEBonusStableDate"; foreach (var currentYearBonusData in last20YearsStockData) { foreach (var bonusData in currentYearBonusData.Value.Where(x => x.RECORD_DT.Trim() != "")) { bool IsYearDateFormat = DateTime.TryParseExact(bonusData.RECORD_DT, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime result); if (!IsYearDateFormat) { DateTime.TryParseExact(bonusData.RECORD_DT, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out result); } var recordDateMinus6Day = result.AddDays(-6); while (recordDateMinus6Day.DayOfWeek == DayOfWeek.Saturday || recordDateMinus6Day.DayOfWeek == DayOfWeek.Sunday) { recordDateMinus6Day = recordDateMinus6Day.AddDays(-1); } tempDt = recordDateMinus6Day.ToString("MM-dd-yy").Split("-"); stringKey = tempDt[1] + tempDt[0] + tempDt[2]; var downloadFilePath = @"C:\Trading\BhavCopy\Last10Year\" + stringKey + ".zip"; try { myWebClient.DownloadFile("https://www1.nseindia.com/archives/equities/bhavcopy/pr/PR" + stringKey + ".zip", downloadFilePath); } catch (Exception ex) { recordDateMinus6Day = recordDateMinus6Day.AddDays(-1); while (recordDateMinus6Day.DayOfWeek == DayOfWeek.Saturday || recordDateMinus6Day.DayOfWeek == DayOfWeek.Sunday) { recordDateMinus6Day = recordDateMinus6Day.AddDays(-1); } tempDt = recordDateMinus6Day.ToString("MM-dd-yy").Split("-"); stringKey = tempDt[1] + tempDt[0] + tempDt[2]; downloadFilePath = @"C:\Trading\BhavCopy\Last10Year\" + stringKey + ".zip"; try { myWebClient.DownloadFile("https://www1.nseindia.com/archives/equities/bhavcopy/pr/PR" + stringKey + ".zip", downloadFilePath); } catch { recordDateMinus6Day = recordDateMinus6Day.AddDays(-1); while (recordDateMinus6Day.DayOfWeek == DayOfWeek.Saturday || recordDateMinus6Day.DayOfWeek == DayOfWeek.Sunday) { recordDateMinus6Day = recordDateMinus6Day.AddDays(-1); } tempDt = recordDateMinus6Day.ToString("MM-dd-yy").Split("-"); stringKey = tempDt[1] + tempDt[0] + tempDt[2]; downloadFilePath = @"C:\Trading\BhavCopy\Last10Year\" + stringKey + ".zip"; try { myWebClient.DownloadFile("https://www1.nseindia.com/archives/equities/bhavcopy/pr/PR" + stringKey + ".zip", downloadFilePath); } catch { recordDateMinus6Day = recordDateMinus6Day.AddDays(-1); while (recordDateMinus6Day.DayOfWeek == DayOfWeek.Saturday || recordDateMinus6Day.DayOfWeek == DayOfWeek.Sunday) { recordDateMinus6Day = recordDateMinus6Day.AddDays(-1); } tempDt = recordDateMinus6Day.ToString("MM-dd-yy").Split("-"); stringKey = tempDt[1] + tempDt[0] + tempDt[2]; downloadFilePath = @"C:\Trading\BhavCopy\Last10Year\" + stringKey + ".zip"; myWebClient.DownloadFile("https://www1.nseindia.com/archives/equities/bhavcopy/pr/PR" + stringKey + ".zip", downloadFilePath); } } } try { Directory.Delete(extractPathForStableDate, true); } catch { } System.IO.Compression.ZipFile.ExtractToDirectory(downloadFilePath, extractPathForStableDate, true); CreateXlsxFile(extractPathForStableDate, stringKey); List <StockData> recordDateMinus6DaysStockData = new EpPlusHelper().ReadFromExcel <List <StockData> >(extractPathForStableDate + @"\Pd" + stringKey + ".xlsx", "Pd" + stringKey); var delistFilteredEquityStockDataRMinus6 = recordDateMinus6DaysStockData.FirstOrDefault(x => x.SYMBOL == bonusData.SYMBOL && x.SERIES == "EQ" && !delistedStockSymbols.Contains(x.SYMBOL) && !toBeDelistedStockSymbols.Contains(x.SYMBOL)); // Here, we get stocks which arent delisted or on the delistable notice list. if (delistFilteredEquityStockDataRMinus6 == null) { continue; } bool IsYearDateFormatForRecordDate = DateTime.TryParseExact(bonusData.RECORD_DT, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out result); if (!IsYearDateFormatForRecordDate) { DateTime.TryParseExact(bonusData.RECORD_DT, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out result); } var recordDateAfter = result.AddDays(1); while (recordDateAfter.DayOfWeek == DayOfWeek.Saturday || recordDateAfter.DayOfWeek == DayOfWeek.Sunday) { recordDateAfter = recordDateAfter.AddDays(1); } if (recordDateAfter.Date > DateTime.Today.Date) { continue; } tempDt = recordDateAfter.ToString("MM-dd-yy").Split("-"); stringKey = tempDt[1] + tempDt[0] + tempDt[2]; downloadFilePath = @"C:\Trading\BhavCopy\Last10Year\" + stringKey + ".zip"; try { myWebClient.DownloadFile("https://www1.nseindia.com/archives/equities/bhavcopy/pr/PR" + stringKey + ".zip", downloadFilePath); } catch (Exception ex) { recordDateAfter = recordDateAfter.AddDays(1); while (recordDateAfter.DayOfWeek == DayOfWeek.Saturday || recordDateAfter.DayOfWeek == DayOfWeek.Sunday) { recordDateAfter = recordDateAfter.AddDays(1); } if (recordDateAfter.Date > DateTime.Today.Date) { continue; } tempDt = recordDateAfter.ToString("MM-dd-yy").Split("-"); stringKey = tempDt[1] + tempDt[0] + tempDt[2]; downloadFilePath = @"C:\Trading\BhavCopy\Last10Year\" + stringKey + ".zip"; try { myWebClient.DownloadFile("https://www1.nseindia.com/archives/equities/bhavcopy/pr/PR" + stringKey + ".zip", downloadFilePath); } catch { recordDateAfter = recordDateAfter.AddDays(1); while (recordDateAfter.DayOfWeek == DayOfWeek.Saturday || recordDateAfter.DayOfWeek == DayOfWeek.Sunday) { recordDateAfter = recordDateAfter.AddDays(1); } tempDt = recordDateAfter.ToString("MM-dd-yy").Split("-"); stringKey = tempDt[1] + tempDt[0] + tempDt[2]; downloadFilePath = @"C:\Trading\BhavCopy\Last10Year\" + stringKey + ".zip"; try { myWebClient.DownloadFile("https://www1.nseindia.com/archives/equities/bhavcopy/pr/PR" + stringKey + ".zip", downloadFilePath); } catch { recordDateAfter = recordDateAfter.AddDays(1); while (recordDateAfter.DayOfWeek == DayOfWeek.Saturday || recordDateAfter.DayOfWeek == DayOfWeek.Sunday) { recordDateAfter = recordDateAfter.AddDays(1); } tempDt = recordDateAfter.ToString("MM-dd-yy").Split("-"); stringKey = tempDt[1] + tempDt[0] + tempDt[2]; downloadFilePath = @"C:\Trading\BhavCopy\Last10Year\" + stringKey + ".zip"; myWebClient.DownloadFile("https://www1.nseindia.com/archives/equities/bhavcopy/pr/PR" + stringKey + ".zip", downloadFilePath); } } } try { Directory.Delete(extractPathForStableDate, true); } catch { } System.IO.Compression.ZipFile.ExtractToDirectory(downloadFilePath, extractPathForStableDate, true); CreateXlsxFile(extractPathForStableDate, stringKey); List <StockData> recordDateStockData = new EpPlusHelper().ReadFromExcel <List <StockData> >(extractPathForStableDate + @"\Pd" + stringKey + ".xlsx", "Pd" + stringKey); var delistFilteredEquityStockDataRDate = recordDateStockData.FirstOrDefault(x => x.SYMBOL == bonusData.SYMBOL && x.SERIES == "EQ" && !delistedStockSymbols.Contains(x.SYMBOL) && !toBeDelistedStockSymbols.Contains(x.SYMBOL)); // Here, we get stocks which arent delisted or on the delistable notice list. if (delistFilteredEquityStockDataRDate == null) { continue; } // Only if after giving Bonus has led to atleast 40 % profit overall: if (decimal.Parse(delistFilteredEquityStockDataRDate.CLOSE_PRICE) * (1m + Decimal.Parse(bonusData.PURPOSE)) >= 1.40m * (decimal.Parse(delistFilteredEquityStockDataRMinus6.CLOSE_PRICE))) { if (!symbolWiseBonuses.ContainsKey(bonusData.SYMBOL)) { symbolWiseBonuses.Add(bonusData.SYMBOL, new List <BonusDataOutput> { new BonusDataOutput { RecordDate = bonusData.RECORD_DT, BonusRatio = bonusData.PURPOSE.Trim(), ClosePriceOnRPlus1Date = decimal.Parse(delistFilteredEquityStockDataRDate.CLOSE_PRICE), ClosePriceOnRMinus6Date = decimal.Parse(delistFilteredEquityStockDataRMinus6.CLOSE_PRICE) } }); } else if (!symbolWiseBonuses[bonusData.SYMBOL].Exists(x => x.RecordDate.Trim() == bonusData.RECORD_DT.Trim())) { symbolWiseBonuses[bonusData.SYMBOL].Add(new BonusDataOutput { RecordDate = bonusData.RECORD_DT, BonusRatio = bonusData.PURPOSE.Trim(), ClosePriceOnRPlus1Date = decimal.Parse(delistFilteredEquityStockDataRDate.CLOSE_PRICE), ClosePriceOnRMinus6Date = decimal.Parse(delistFilteredEquityStockDataRMinus6.CLOSE_PRICE) }); } } } } var historicalBonusShareData = symbolWiseBonuses.OrderByDescending(x => x.Value.Count); string json = JsonConvert.SerializeObject(historicalBonusShareData, Formatting.Indented); Console.WriteLine("Historical Share Bonus Data: -----\n" + json + "\n-------------\n"); var upcomingStocksWithGenuineBonus = stocksWhichHaveBeenAnnounced.Where(x => historicalBonusShareData.Select(y => y.Key).Contains(x.SYMBOL)); string upcomingGenuineStockBonuses = JsonConvert.SerializeObject(upcomingStocksWithGenuineBonus, Formatting.Indented); Console.WriteLine("Upcoming Genuine Stock Bonus Data: -----\n" + upcomingGenuineStockBonuses + "\n-------------\n"); Console.ReadLine(); }
static void Main(string[] args) { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); WebClient myWebClient = new WebClient(); Dictionary <string, decimal?> currentStockValue = new Dictionary <string, decimal?>(); Dictionary <string, decimal?> stocksAndTheirHighAvgd = new Dictionary <string, decimal?>(); Dictionary <string, decimal?> stocksAndTheirLowAvgd = new Dictionary <string, decimal?>(); Dictionary <string, List <DividendData> > last20YearsStockData = new Dictionary <string, List <DividendData> >(); Dictionary <string, List <DividendDataOutput> > symbolWiseBonuses = new Dictionary <string, List <DividendDataOutput> >(); Dictionary <string, int> hasDailyStdDevBeenHigherThan30percentAvgStdDevDays = new Dictionary <string, int>(); myWebClient.DownloadFile("https://archives.nseindia.com/content/equities/Companies_proposed_to_be_delisted.xlsx", @"C:\Trading\BhavCopy\Last50DaysNSE\ToBeDelistedStockSymbols.xlsx"); myWebClient.DownloadFile("https://archives.nseindia.com/content/equities/delisted.xlsx", @"C:\Trading\BhavCopy\Last50DaysNSE\DelistedStockSymbols.xlsx"); List <string> delistedStockSymbols = new EpPlusHelper().ReadFromExcel <List <DelistedStockData> >(@"C:\Trading\BhavCopy\Last50DaysNSE\DelistedStockSymbols.xlsx", "delisted").Select(x => x.Symbol).ToList(); List <string> toBeDelistedStockSymbols = new EpPlusHelper().ReadFromExcel <List <ToBeDelistedStockData> >(@"C:\Trading\BhavCopy\Last50DaysNSE\ToBeDelistedStockSymbols.xlsx", "Sheet1").Select(x => x.Symbol).ToList(); var stocksWhichHaveBeenAnnounced = new List <DividendData>(); var consideredDate = DateTime.Now.Date.AddDays(-1); while (consideredDate.DayOfWeek == DayOfWeek.Saturday || consideredDate.DayOfWeek == DayOfWeek.Sunday) { consideredDate = consideredDate.AddDays(-1); } var tempDt = consideredDate.ToString("dd-MM-yy").Split("-"); var stringKey = tempDt[0] + tempDt[1] + tempDt[2]; try { var downloadFilePath = @"C:\Trading\BhavCopy\Last10Year\" + stringKey + ".zip"; var extractPath = @"C:\Trading\BhavCopy\NSEBonus"; myWebClient.DownloadFile("https://www1.nseindia.com/archives/equities/bhavcopy/pr/PR" + stringKey + ".zip", downloadFilePath); try { Directory.Delete(extractPath, true); } catch { } System.IO.Compression.ZipFile.ExtractToDirectory(downloadFilePath, extractPath, true); CreateBcXlsxFile(extractPath, stringKey); List <DividendData> bonusAndDividendData = new EpPlusHelper().ReadFromExcel <List <DividendData> >(extractPath + @"\Bc" + stringKey + ".xlsx", "Bc" + stringKey); var delistFilteredEquityBonusData = bonusAndDividendData.Where(x => x.PURPOSE != null && x.PURPOSE.Contains("RIGHTS") && x.SERIES != null && x.SERIES == "EQ" && x.SYMBOL != null && !delistedStockSymbols.Contains(x.SYMBOL) && !toBeDelistedStockSymbols.Contains(x.SYMBOL)).ToList(); var bonusUpcomingStockData = delistFilteredEquityBonusData.Where(x => Convert.ToDateTime(x.EX_DT) > DateTime.Today.AddDays(2)).Select(x => new DividendData { SYMBOL = x.SYMBOL, EX_DT = x.EX_DT.Replace("/", "-").Trim(), PURPOSE = x.PURPOSE.Trim() }); stocksWhichHaveBeenAnnounced.AddRange(bonusUpcomingStockData); } catch (Exception ex) { } foreach (int month in Enumerable.Range(0, 300).ToList()) { consideredDate = DateTime.Now.Date.AddDays(-1).AddMonths(-month); while (consideredDate.DayOfWeek == DayOfWeek.Saturday || consideredDate.DayOfWeek == DayOfWeek.Sunday) { consideredDate = consideredDate.AddDays(-1); } tempDt = consideredDate.ToString("MM-dd-yy").Split("-"); stringKey = tempDt[1] + tempDt[0] + tempDt[2]; try { var downloadFilePath = @"C:\Trading\BhavCopy\Last10Year\" + stringKey + ".zip"; var extractPath = @"C:\Trading\BhavCopy\NSEBonus"; myWebClient.DownloadFile("https://www1.nseindia.com/archives/equities/bhavcopy/pr/PR" + stringKey + ".zip", downloadFilePath); try { Directory.Delete(extractPath, true); } catch { } System.IO.Compression.ZipFile.ExtractToDirectory(downloadFilePath, extractPath, true); CreateBcXlsxFile(extractPath, stringKey); List <DividendData> bonusAndDividendData = new EpPlusHelper().ReadFromExcel <List <DividendData> >(extractPath + @"\Bc" + stringKey + ".xlsx", "Bc" + stringKey); var delistFilteredEquityBonusData = bonusAndDividendData.Where(x => x.PURPOSE != null && x.PURPOSE.Contains("RIGHTS") && x.SERIES != null && x.SERIES == "EQ" && x.SYMBOL != null && !delistedStockSymbols.Contains(x.SYMBOL) && !toBeDelistedStockSymbols.Contains(x.SYMBOL)).ToList(); if (delistFilteredEquityBonusData.Count() > 0) { var bonusStockData = delistFilteredEquityBonusData.Select(x => new DividendData { SYMBOL = x.SYMBOL, EX_DT = x.EX_DT.Replace("/", "-").Trim(), PURPOSE = x.PURPOSE.Trim() }); last20YearsStockData.Add(stringKey, bonusStockData.ToList()); } } catch (Exception ex) { continue; } } Dictionary <string, int> daysForWhichBonusIsStable = new Dictionary <string, int>(); foreach (var currentYearBonusData in last20YearsStockData) { foreach (var bonusData in currentYearBonusData.Value.Where(x => x.EX_DT.Trim() != "")) { bool IsYearDateFormat = DateTime.TryParseExact(bonusData.EX_DT, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime result); if (!IsYearDateFormat) { DateTime.TryParseExact(bonusData.EX_DT, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out result); } bonusData.EX_DT = result.ToString("dd-MM-yyyy"); } } var historicalRightsIssueData = last20YearsStockData.OrderByDescending(x => x.Value.Count); string json = JsonConvert.SerializeObject(historicalRightsIssueData, Formatting.Indented); Console.WriteLine("Historical Share Rights Data: -----\n" + json + "\n-------------\n"); var upcomingStocksWithGenuineRights = stocksWhichHaveBeenAnnounced.Where(x => historicalRightsIssueData.Select(y => y.Key).Contains(x.SYMBOL)); string upcomingGenuineStockRights = JsonConvert.SerializeObject(upcomingStocksWithGenuineRights, Formatting.Indented); Console.WriteLine("Upcoming Genuine Stock Bonus Data: -----\n" + upcomingGenuineStockRights + "\n-------------\n"); Console.ReadLine(); }