Esempio n. 1
0
        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");
            myWebClient.DownloadFile("https://www1.nseindia.com/content/equities/suspension.xls", @"C:\Trading\BhavCopy\Rachana\EVEBITDA\SuspendedStockSymbols.xls");
            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();
            List <string> suspendedStockSymbols1   = EpPlusHelper.ReadExcel <List <NSE.ToBeDelistedStockData> >(@"C:\Trading\BhavCopy\Rachana\EVEBITDA\SuspendedStockSymbols.xls", "Suspension prior SOP").Select(x => x.Symbol).ToList();
            List <string> suspendedStockSymbols2   = EpPlusHelper.ReadExcel <List <NSE.ToBeDelistedStockData> >(@"C:\Trading\BhavCopy\Rachana\EVEBITDA\SuspendedStockSymbols.xls", "SOP Suspended").Select(x => x.Symbol).ToList();
            List <string> suspendedStockSymbols3   = EpPlusHelper.ReadExcel <List <NSE.ToBeDelistedStockData> >(@"C:\Trading\BhavCopy\Rachana\EVEBITDA\SuspendedStockSymbols.xls", "Liquidation").Select(x => x.Symbol).ToList();
            List <string> suspendedStockSymbols4   = EpPlusHelper.ReadExcel <List <NSE.ToBeDelistedStockData> >(@"C:\Trading\BhavCopy\Rachana\EVEBITDA\SuspendedStockSymbols.xls", "Surveillence measures").Select(x => x.Symbol).ToList();
            List <string> suspendedStockSymbols5   = EpPlusHelper.ReadExcel <List <NSE.ToBeDelistedStockData> >(@"C:\Trading\BhavCopy\Rachana\EVEBITDA\SuspendedStockSymbols.xls", "ALF suspended").Select(x => x.Symbol).ToList();
            List <string> suspendedStockSymbols6   = EpPlusHelper.ReadExcel <List <NSE.ToBeDelistedStockData> >(@"C:\Trading\BhavCopy\Rachana\EVEBITDA\SuspendedStockSymbols.xls", "OTHERS").Select(x => x.Symbol).ToList();
            List <string> suspendedStockSymbolsAll = suspendedStockSymbols1.Union(suspendedStockSymbols2).Union(suspendedStockSymbols3).Union(suspendedStockSymbols4).Union(suspendedStockSymbols5).Union(suspendedStockSymbols6).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>();

            // In the below computation from line # 41 till # 65, we get list of all stocks with their (High-Low-Open-Close-Traded Qty-Net Value against each stock and filter out delisted and suspended stocks. These stocks however have upper circuit and lower circuit stocks)
            // The variable : last100DaysStockData contains this data.
            foreach (int item in Enumerable.Range(1, 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" && x.OPEN_PRICE != null && x.OPEN_PRICE != "" && Decimal.TryParse(x.OPEN_PRICE, out decimal openPriceTemp) && openPriceTemp > 50m && !delistedStockSymbols.Contains(x.SYMBOL) && !toBeDelistedStockSymbols.Contains(x.SYMBOL) && !suspendedStockSymbolsAll.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; }
                }
            }

            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>();

            foreach (var symbol in exponentialFactorPerStock.Keys)
            {
                exponentialVwapPerStock.Add(symbol, exponentialVwapAggregateForDayPerStock[symbol] / denominatorCountAggregateForVwapCalculationPerStock[symbol]);
            }
            // Calculate the Exponential VWap per stocks taken exponentially for the last 100 days.
            // Example :  If Yesterday's VWap = 100 and Day Before Yesterday's Vwap = 110, then exponential VWap for 2 days,
            // then taking a sample weight of 100, we have ((100 * 100) + (99 * 110))/(100 +99)) = 104.97

            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" && x.OPEN_PRICE != null && x.OPEN_PRICE != "" && Decimal.TryParse(x.OPEN_PRICE, out decimal openPriceTemp) && openPriceTemp > 50m && !delistedStockSymbols.Contains(x.SYMBOL) && !toBeDelistedStockSymbols.Contains(x.SYMBOL) && !suspendedStockSymbolsAll.Contains(x.SYMBOL)).ToList();

                    foreach (var delistFilteredStock in delistFilteredEquityStockData.OrderBy(x => x.CLOSE_PRICE))
                    {
                        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(120000);
                        }
                        counter++;
                        // Right now, its a headache to run this progrm as it takes very very long amount of time to execute. (Maybe like 1 .5 days continuiusly due to waiting for 2 mins every other request.
                        // Issue is with google returning 429 (Too many requests from a single IP error whenever I change this value below 2 mins / 2 requests)
                        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();
                                // MoneyControl Symbol Code is different than the NSE Symbol.
                                var moneyControlSymbolCode = data.Split("https://www.moneycontrol.com/stocks/company_info/stock_news.php%3Fsc_id%3D")[1].Split("%")[0];
                                response.Close();
                                readStream.Close();

                                // Get the consolidated balance sheet from money control.
                                string         urlAddressForBalanceSheet = "https://www.moneycontrol.com/financials/britanniaindustries/consolidated-balance-sheetVI/" + moneyControlSymbolCode + "#" + moneyControlSymbolCode;
                                HttpWebRequest requestForBalanceSheet    = (HttpWebRequest)WebRequest.Create(urlAddressForBalanceSheet);
                                requestForBalanceSheet.Headers.Add("User-Agent", @"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5)\AppleWebKit / 537.36(KHTML, like Gecko) Safari / 537.36");
                                HttpWebResponse responseForBalanceSheet      = (HttpWebResponse)requestForBalanceSheet.GetResponse();
                                Stream          receiveStreamForBalanceSheet = responseForBalanceSheet.GetResponseStream();
                                StreamReader    readStreamForBalanceSheet    = string.IsNullOrWhiteSpace(responseForBalanceSheet.CharacterSet) ? new StreamReader(receiveStreamForBalanceSheet) : new StreamReader(receiveStreamForBalanceSheet, Encoding.GetEncoding(responseForBalanceSheet.CharacterSet));
                                string          balanceSheetData             = readStreamForBalanceSheet.ReadToEnd();

                                if (balanceSheetData.Split("Long Term Borrowings").Length <= 1)
                                {
                                    continue;
                                }

                                decimal longTermBorrowings  = decimal.Parse(balanceSheetData.Split("Long Term Borrowings")[1].Split("<td>")[1].Split("</td>")[0]);
                                decimal shortTermBorrowings = decimal.Parse(balanceSheetData.Split("Short Term Borrowings")[1].Split("<td>")[1].Split("</td>")[0]);
                                decimal debt = longTermBorrowings + shortTermBorrowings;
                                decimal cashAndCashEquivalents = decimal.Parse(balanceSheetData.Split("Cash And Cash Equivalents")[1].Split("<td>")[1].Split("</td>")[0]);
                                // We need the above values like Debt and Cash&Cash Equivalents(CCE). We need the above data to capture the Enterprise Value.
                                // Net Debt = Debt - CCE [ Debt - CCE ]
                                // Enterprise Value (EV) = [NetDebt + MarketCap] in Crores.

                                string         urlAddressForConsolidatedAnnualResults = "https://www.moneycontrol.com/financials/britanniaindustries/results/consolidated-yearly/" + moneyControlSymbolCode + "#" + moneyControlSymbolCode;
                                HttpWebRequest requestForConsolidatedAnnualResults    = (HttpWebRequest)WebRequest.Create(urlAddressForConsolidatedAnnualResults);
                                requestForConsolidatedAnnualResults.Headers.Add("User-Agent", @"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5)\AppleWebKit / 537.36(KHTML, like Gecko) Safari / 537.36");
                                HttpWebResponse responseForConsolidatedAnnualResults      = (HttpWebResponse)requestForConsolidatedAnnualResults.GetResponse();
                                Stream          receiveStreamForConsolidatedAnnualResults = responseForConsolidatedAnnualResults.GetResponseStream();
                                StreamReader    readStreamForConsolidatedAnnualResults    = string.IsNullOrWhiteSpace(responseForConsolidatedAnnualResults.CharacterSet) ? new StreamReader(receiveStreamForConsolidatedAnnualResults) : new StreamReader(receiveStreamForConsolidatedAnnualResults, Encoding.GetEncoding(responseForConsolidatedAnnualResults.CharacterSet));
                                string          consolidatedAnnualResultsData             = readStreamForConsolidatedAnnualResults.ReadToEnd();

                                if (consolidatedAnnualResultsData.Split("P/L Before Int., Excpt. Items &amp; Tax").Length <= 1)
                                {
                                    continue;
                                }

                                // Year1 'Profit Before Tax, Depreciation & Amortization' = Last March 2020 PBT (After April 2021, we would be getting March 2021 PBT automatically in this code.)
                                var year1PLBeforeTaxDepreciationString = System.Text.RegularExpressions.Regex.Replace(consolidatedAnnualResultsData.Split("P/L Before Int., Excpt. Items &amp; Tax")[1].Split("<td>")[1], "[^0-9.]", "");

                                // Year2 'Profit Before Tax, Depreciation & Amortization' = March 2019 PBT (After April 2021, we would be getting March 2020 PBT automatically in this code.)
                                var year2PLBeforeTaxDepreciationString = System.Text.RegularExpressions.Regex.Replace(consolidatedAnnualResultsData.Split("P/L Before Int., Excpt. Items &amp; Tax")[1].Split("<td>")[2], "[^0-9.]", "");

                                // Year3 'Profit Before Tax, Depreciation & Amortization' = March 2018 PBT (After April 2021, we would be getting March 2019 PBT automatically in this code.)
                                var year3PLBeforeTaxDepreciationString = System.Text.RegularExpressions.Regex.Replace(consolidatedAnnualResultsData.Split("P/L Before Int., Excpt. Items &amp; Tax")[1].Split("<td>")[3], "[^0-9.]", "");

                                // Year4 'Profit Before Tax, Depreciation & Amortization' = March 2017 PBT (After April 2021, we would be getting March 2018 PBT automatically in this code.)
                                var year4PLBeforeTaxDepreciationString = System.Text.RegularExpressions.Regex.Replace(consolidatedAnnualResultsData.Split("P/L Before Int., Excpt. Items &amp; Tax")[1].Split("<td>")[4], "[^0-9.]", "");

                                Decimal.TryParse(year1PLBeforeTaxDepreciationString, out decimal year1PLBeforeTaxDepreciation);
                                Decimal.TryParse(year2PLBeforeTaxDepreciationString, out decimal year2PLBeforeTaxDepreciation);
                                Decimal.TryParse(year3PLBeforeTaxDepreciationString, out decimal year3PLBeforeTaxDepreciation);
                                Decimal.TryParse(year4PLBeforeTaxDepreciationString, out decimal year4PLBeforeTaxDepreciation);

                                decimal PLBeforeTaxDepreciationLast4YearsAggregate = year1PLBeforeTaxDepreciation + year2PLBeforeTaxDepreciation + year3PLBeforeTaxDepreciation + year4PLBeforeTaxDepreciation;

                                var year1DepreciationString = System.Text.RegularExpressions.Regex.Replace(consolidatedAnnualResultsData.Split("Depreciation")[1].Split("<td>")[1], "[^0-9.]", "");
                                var year2DepreciationString = System.Text.RegularExpressions.Regex.Replace(consolidatedAnnualResultsData.Split("Depreciation")[1].Split("<td>")[2], "[^0-9.]", "");
                                var year3DepreciationString = System.Text.RegularExpressions.Regex.Replace(consolidatedAnnualResultsData.Split("Depreciation")[1].Split("<td>")[3], "[^0-9.]", "");
                                var year4DepreciationString = System.Text.RegularExpressions.Regex.Replace(consolidatedAnnualResultsData.Split("Depreciation")[1].Split("<td>")[4], "[^0-9.]", "");

                                Decimal.TryParse(year1DepreciationString, out decimal year1Depreciation);
                                Decimal.TryParse(year2DepreciationString, out decimal year2Depreciation);
                                Decimal.TryParse(year3DepreciationString, out decimal year3Depreciation);
                                Decimal.TryParse(year4DepreciationString, out decimal year4Depreciation);

                                decimal DepreciationLast4YearsAggregate = year1Depreciation + year2Depreciation + year3Depreciation + year4Depreciation;

                                var EBITDAYear1 = (year1PLBeforeTaxDepreciation + year1Depreciation); // EBITDA for 2020
                                var EBITDAYear4 = (year4PLBeforeTaxDepreciation + year4Depreciation); // EBITDA for 2017

                                // CAGR of the company when comparing the results of 2020 and comparing the results of 2017.
                                // Formula for CAGR is ("2020 EBITDA" / "2017 EBITDA")^(1/n) - 1; // So, here, n = number of years difference = 3 (2020 - 2017).
                                var latest3yearEBITDACAGR = Math.Pow((double)EBITDAYear1 / (double)EBITDAYear4, 0.334) - 1;

                                // Consolidated EBITDA for the last 4 years.
                                decimal consolidatedEBITDA = PLBeforeTaxDepreciationLast4YearsAggregate + DepreciationLast4YearsAggregate;

                                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                = Convert.ToInt64((singleMCapData.MarketCap * Convert.ToDecimal(Math.Pow(10, 7))) / (decimal)singleMCapData.LastPrice); // * 10^7  = 1 Crore. So, since the money control api & site has the Market Cap in crores, we multiply by 10^7. Ultimately we need to get the # of shares of the company. It can also be gotten from Shareholder pattern in moneycontrol site but could not get a way to do it programatically.
                                    singleMCapData.ExponentialVwapValue      = exponentialVwapPerStock[delistFilteredStock.SYMBOL];
                                    singleMCapData.ComputedMarketCapInCrores = singleMCapData.ExponentialVwapValue * singleMCapData.NoOfShares / (decimal)Math.Pow(10, 7);
                                    singleMCapData.ComputedDebt              = debt;
                                    singleMCapData.ComputedCCE               = cashAndCashEquivalents;
                                    singleMCapData.ComputedEnterpriseValue   = singleMCapData.ComputedMarketCapInCrores + debt - cashAndCashEquivalents; // Get the current EV as per exponential VWAP.
                                    singleMCapData.ComputedEBITDA            = consolidatedEBITDA;
                                    singleMCapData.ComputedNetDebt           = debt - cashAndCashEquivalents;
                                    singleMCapData.EVEBITDARatio             = singleMCapData.ComputedEnterpriseValue / singleMCapData.ComputedEBITDA;    // (EV/EBITDA) ratio is important to calucate the estimated share price next quarter.
                                    singleMCapData.LatestYearEBITDACAGR      = Convert.ToDecimal(latest3yearEBITDACAGR);
                                    var estimatedEBITDA             = singleMCapData.ComputedEBITDA * (1 + (singleMCapData.LatestYearEBITDACAGR / 100m)); // Estimated EBITDA next year would be = [(Calculated EBITDA this year) * ( 1 + CAGR)]
                                    var expectedEV                  = singleMCapData.EVEBITDARatio * estimatedEBITDA;                                     // (Static EV/EBITDA calculated in line # 240 * Estimated EBITDA for next year calcuated in above line)
                                    var expectedEquityValueInRupees = (expectedEV - singleMCapData.ComputedNetDebt) * Convert.ToDecimal(Math.Pow(10, 7));
                                    singleMCapData.ExpectedPriceValueNextYear = expectedEquityValueInRupees / (decimal)singleMCapData.NoOfShares;         // If # of shares is staying constant next year as well, then expected share value next year would be = [Expected Equity Value / # Of Shares]

                                    //Rachana Ranade actually mentioned till above point to evaluate the expected price value for March 2021 based on the EBITDA CAGR of 2017 (or of any previous year for that matter) AND (current share value)
                                    if (singleMCapData.ExpectedPriceValueNextYear >= 1.15m * singleMCapData.LastPrice)
                                    {
                                        // Expected Price / Todays Price suggests the % increase when compared to today's price. If expected price is greater than 15% of today's price, then it would be a good valuation to buy according to me . Rachana didnt suggest anything about this though.
                                        singleMCapData.ExpectedPriceLastPriceRatio = singleMCapData.ExpectedPriceValueNextYear / singleMCapData.LastPrice;
                                        MCapData.Add(singleMCapData);
                                    }
                                }
                            }
                        }
                        catch (Exception ex2)
                        {
                            // Exception occurs if the Profit Loss statements arent available in Money Control for the given company.
                        }
                    }
                }
                catch (Exception ex3) { }
            }
            // PRogram is a little error prone due to Google not returning the right MoneyControl Code. However, this error is easily caught
            // by checking the CompanyName & Company Symbol in the below response. Only if its matching, then its an accurate result as per this program.
            Console.WriteLine(JsonConvert.SerializeObject(MCapData.OrderByDescending(x => x.ExpectedPriceLastPriceRatio)));
            Console.ReadLine();
        }
Esempio n. 2
0
        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");
            myWebClient.DownloadFile("https://www1.nseindia.com/content/equities/suspension.xls", @"C:\Trading\BhavCopy\Rachana\EVEBITDA\SuspendedStockSymbols.xls");
            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();
            List <string> suspendedStockSymbols1   = EpPlusHelper.ReadExcel <List <NSE.ToBeDelistedStockData> >(@"C:\Trading\BhavCopy\Rachana\EVEBITDA\SuspendedStockSymbols.xls", "Suspension prior SOP").Select(x => x.Symbol).ToList();
            List <string> suspendedStockSymbols2   = EpPlusHelper.ReadExcel <List <NSE.ToBeDelistedStockData> >(@"C:\Trading\BhavCopy\Rachana\EVEBITDA\SuspendedStockSymbols.xls", "SOP Suspended").Select(x => x.Symbol).ToList();
            List <string> suspendedStockSymbols3   = EpPlusHelper.ReadExcel <List <NSE.ToBeDelistedStockData> >(@"C:\Trading\BhavCopy\Rachana\EVEBITDA\SuspendedStockSymbols.xls", "Liquidation").Select(x => x.Symbol).ToList();
            List <string> suspendedStockSymbols4   = EpPlusHelper.ReadExcel <List <NSE.ToBeDelistedStockData> >(@"C:\Trading\BhavCopy\Rachana\EVEBITDA\SuspendedStockSymbols.xls", "Surveillence measures").Select(x => x.Symbol).ToList();
            List <string> suspendedStockSymbols5   = EpPlusHelper.ReadExcel <List <NSE.ToBeDelistedStockData> >(@"C:\Trading\BhavCopy\Rachana\EVEBITDA\SuspendedStockSymbols.xls", "ALF suspended").Select(x => x.Symbol).ToList();
            List <string> suspendedStockSymbols6   = EpPlusHelper.ReadExcel <List <NSE.ToBeDelistedStockData> >(@"C:\Trading\BhavCopy\Rachana\EVEBITDA\SuspendedStockSymbols.xls", "OTHERS").Select(x => x.Symbol).ToList();
            List <string> suspendedStockSymbolsAll = suspendedStockSymbols1.Union(suspendedStockSymbols2).Union(suspendedStockSymbols3).Union(suspendedStockSymbols4).Union(suspendedStockSymbols5).Union(suspendedStockSymbols6).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(1, 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" && x.OPEN_PRICE != null && x.OPEN_PRICE != "" && Decimal.TryParse(x.OPEN_PRICE, out decimal openPriceTemp) && openPriceTemp > 50m && !delistedStockSymbols.Contains(x.SYMBOL) && !toBeDelistedStockSymbols.Contains(x.SYMBOL) && !suspendedStockSymbolsAll.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; }
                }
            }

            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>();

            foreach (var symbol in exponentialFactorPerStock.Keys)
            {
                exponentialVwapPerStock.Add(symbol, exponentialVwapAggregateForDayPerStock[symbol] / denominatorCountAggregateForVwapCalculationPerStock[symbol]);
            }

            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" && x.OPEN_PRICE != null && x.OPEN_PRICE != "" && Decimal.TryParse(x.OPEN_PRICE, out decimal openPriceTemp) && openPriceTemp > 50m && !delistedStockSymbols.Contains(x.SYMBOL) && !toBeDelistedStockSymbols.Contains(x.SYMBOL) && !suspendedStockSymbolsAll.Contains(x.SYMBOL)).ToList();

                    foreach (var delistFilteredStock in delistFilteredEquityStockData.OrderBy(x => x.CLOSE_PRICE))
                    {
                        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(120000);
                        }
                        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];
                                response.Close();
                                readStream.Close();

                                string         urlAddressForBalanceSheet = "https://www.moneycontrol.com/financials/britanniaindustries/consolidated-balance-sheetVI/" + moneyControlSymbolCode + "#" + moneyControlSymbolCode;
                                HttpWebRequest requestForBalanceSheet    = (HttpWebRequest)WebRequest.Create(urlAddressForBalanceSheet);
                                requestForBalanceSheet.Headers.Add("User-Agent", @"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5)\AppleWebKit / 537.36(KHTML, like Gecko) Safari / 537.36");
                                HttpWebResponse responseForBalanceSheet      = (HttpWebResponse)requestForBalanceSheet.GetResponse();
                                Stream          receiveStreamForBalanceSheet = responseForBalanceSheet.GetResponseStream();
                                StreamReader    readStreamForBalanceSheet    = string.IsNullOrWhiteSpace(responseForBalanceSheet.CharacterSet) ? new StreamReader(receiveStreamForBalanceSheet) : new StreamReader(receiveStreamForBalanceSheet, Encoding.GetEncoding(responseForBalanceSheet.CharacterSet));
                                string          balanceSheetData             = readStreamForBalanceSheet.ReadToEnd();

                                if (balanceSheetData.Split("Long Term Borrowings").Length <= 1)
                                {
                                    continue;
                                }

                                decimal longTermBorrowings  = decimal.Parse(balanceSheetData.Split("Long Term Borrowings")[1].Split("<td>")[1].Split("</td>")[0]);
                                decimal shortTermBorrowings = decimal.Parse(balanceSheetData.Split("Short Term Borrowings")[1].Split("<td>")[1].Split("</td>")[0]);
                                decimal debt = longTermBorrowings + shortTermBorrowings;
                                decimal cashAndCashEquivalents = decimal.Parse(balanceSheetData.Split("Cash And Cash Equivalents")[1].Split("<td>")[1].Split("</td>")[0]);

                                string         urlAddressForConsolidatedQuarterlyResults = "https://www.moneycontrol.com/financials/britanniaindustries/results/consolidated-quarterly-results/" + moneyControlSymbolCode + "#" + moneyControlSymbolCode;
                                HttpWebRequest requestForConsolidatedQuarterlyResults    = (HttpWebRequest)WebRequest.Create(urlAddressForConsolidatedQuarterlyResults);
                                requestForConsolidatedQuarterlyResults.Headers.Add("User-Agent", @"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5)\AppleWebKit / 537.36(KHTML, like Gecko) Safari / 537.36");
                                HttpWebResponse responseForConsolidatedQuarterlyResults      = (HttpWebResponse)requestForConsolidatedQuarterlyResults.GetResponse();
                                Stream          receiveStreamForConsolidatedQuarterlyResults = responseForConsolidatedQuarterlyResults.GetResponseStream();
                                StreamReader    readStreamForConsolidatedQuarterlyResults    = string.IsNullOrWhiteSpace(responseForConsolidatedQuarterlyResults.CharacterSet) ? new StreamReader(receiveStreamForConsolidatedQuarterlyResults) : new StreamReader(receiveStreamForConsolidatedQuarterlyResults, Encoding.GetEncoding(responseForConsolidatedQuarterlyResults.CharacterSet));
                                string          consolidatedQuarterlyResultsData             = readStreamForConsolidatedQuarterlyResults.ReadToEnd();

                                if (consolidatedQuarterlyResultsData.Split("P/L Before Int., Excpt. Items &amp; Tax").Length <= 1)
                                {
                                    continue;
                                }

                                var quarter1PLBeforeTaxDepreciationString = System.Text.RegularExpressions.Regex.Replace(consolidatedQuarterlyResultsData.Split("P/L Before Int., Excpt. Items &amp; Tax")[1].Split("<td>")[1], "[^0-9.]", "");
                                var quarter2PLBeforeTaxDepreciationString = System.Text.RegularExpressions.Regex.Replace(consolidatedQuarterlyResultsData.Split("P/L Before Int., Excpt. Items &amp; Tax")[1].Split("<td>")[2], "[^0-9.]", "");
                                var quarter3PLBeforeTaxDepreciationString = System.Text.RegularExpressions.Regex.Replace(consolidatedQuarterlyResultsData.Split("P/L Before Int., Excpt. Items &amp; Tax")[1].Split("<td>")[3], "[^0-9.]", "");
                                var quarter4PLBeforeTaxDepreciationString = System.Text.RegularExpressions.Regex.Replace(consolidatedQuarterlyResultsData.Split("P/L Before Int., Excpt. Items &amp; Tax")[1].Split("<td>")[4], "[^0-9.]", "");

                                Decimal.TryParse(quarter1PLBeforeTaxDepreciationString, out decimal quarter1PLBeforeTaxDepreciation);
                                Decimal.TryParse(quarter2PLBeforeTaxDepreciationString, out decimal quarter2PLBeforeTaxDepreciation);
                                Decimal.TryParse(quarter3PLBeforeTaxDepreciationString, out decimal quarter3PLBeforeTaxDepreciation);
                                Decimal.TryParse(quarter4PLBeforeTaxDepreciationString, out decimal quarter4PLBeforeTaxDepreciation);

                                decimal PLBeforeTaxDepreciationLast4QuartersAggregate = quarter1PLBeforeTaxDepreciation + quarter2PLBeforeTaxDepreciation + quarter3PLBeforeTaxDepreciation + quarter4PLBeforeTaxDepreciation;

                                var quarter1DepreciationString = System.Text.RegularExpressions.Regex.Replace(consolidatedQuarterlyResultsData.Split("Depreciation")[1].Split("<td>")[1], "[^0-9.]", "");
                                var quarter2DepreciationString = System.Text.RegularExpressions.Regex.Replace(consolidatedQuarterlyResultsData.Split("Depreciation")[1].Split("<td>")[2], "[^0-9.]", "");
                                var quarter3DepreciationString = System.Text.RegularExpressions.Regex.Replace(consolidatedQuarterlyResultsData.Split("Depreciation")[1].Split("<td>")[3], "[^0-9.]", "");
                                var quarter4DepreciationString = System.Text.RegularExpressions.Regex.Replace(consolidatedQuarterlyResultsData.Split("Depreciation")[1].Split("<td>")[4], "[^0-9.]", "");

                                Decimal.TryParse(quarter1DepreciationString, out decimal quarter1Depreciation);
                                Decimal.TryParse(quarter2DepreciationString, out decimal quarter2Depreciation);
                                Decimal.TryParse(quarter3DepreciationString, out decimal quarter3Depreciation);
                                Decimal.TryParse(quarter4DepreciationString, out decimal quarter4Depreciation);

                                decimal DepreciationLast4QuartersAggregate = quarter1Depreciation + quarter2Depreciation + quarter3Depreciation + quarter4Depreciation;

                                //In Rachana Ranade's document, she compared 2017 to 2020's EBITDA from Annual Rpeorts.
                                //In my case, I am comparing only last quarter to this quarter(Q1 and Q2 of above variables) EBITDA to speculate the next quarters EBIDTA and compare based on higher growth spurts.

                                var EBITDAQuarter1            = (quarter1PLBeforeTaxDepreciation + quarter1Depreciation);
                                var EBITDAQuarter3            = (quarter3PLBeforeTaxDepreciation + quarter3Depreciation);
                                var latestBiQuarterEBITDACAGR = Math.Pow((double)EBITDAQuarter1 / (double)EBITDAQuarter3, 2) - 1;

                                decimal consolidatedEBITDA = PLBeforeTaxDepreciationLast4QuartersAggregate + DepreciationLast4QuartersAggregate;

                                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                = Convert.ToInt64((singleMCapData.MarketCap * Convert.ToDecimal(Math.Pow(10, 7))) / (decimal)singleMCapData.LastPrice);
                                    singleMCapData.ExponentialVwapValue      = exponentialVwapPerStock[delistFilteredStock.SYMBOL];
                                    singleMCapData.ComputedMarketCapInCrores = singleMCapData.ExponentialVwapValue * singleMCapData.NoOfShares / (decimal)Math.Pow(10, 7);
                                    singleMCapData.ComputedDebt              = debt;
                                    singleMCapData.ComputedCCE               = cashAndCashEquivalents;
                                    singleMCapData.ComputedEnterpriseValue   = singleMCapData.ComputedMarketCapInCrores + debt - cashAndCashEquivalents;
                                    singleMCapData.ComputedEBITDA            = consolidatedEBITDA;
                                    singleMCapData.ComputedNetDebt           = debt - cashAndCashEquivalents;
                                    singleMCapData.EVEBITDARatio             = singleMCapData.ComputedEnterpriseValue / singleMCapData.ComputedEBITDA;
                                    singleMCapData.LatestQuarterEBITDACAGR   = Convert.ToDecimal(latestBiQuarterEBITDACAGR);
                                    var estimatedEBITDA             = singleMCapData.ComputedEBITDA * (1 + (singleMCapData.LatestQuarterEBITDACAGR / 100m));
                                    var expectedEV                  = singleMCapData.EVEBITDARatio * estimatedEBITDA;
                                    var expectedEquityValueInRupees = (expectedEV - singleMCapData.ComputedNetDebt) * Convert.ToDecimal(Math.Pow(10, 7));
                                    singleMCapData.ExpectedPriceValueNextQuarter = expectedEquityValueInRupees / (decimal)singleMCapData.NoOfShares;
                                    if (singleMCapData.ExpectedPriceValueNextQuarter >= 1.4m * singleMCapData.LastPrice)
                                    {
                                        singleMCapData.ExpectedPriceLastPriceRatio = singleMCapData.ExpectedPriceValueNextQuarter / singleMCapData.LastPrice;
                                        MCapData.Add(singleMCapData);
                                    }
                                }
                            }
                        }
                        catch (Exception ex2)
                        {
                        }
                    }
                }
                catch (Exception ex3) { }
            }
            Console.WriteLine(JsonConvert.SerializeObject(MCapData.OrderByDescending(x => x.ExpectedPriceLastPriceRatio)));
            //var screenedStocks = MCapData.Where(X => X.ExpectedPriceValueNextQuarter > 1.22m * X.LastPrice);
            //Console.WriteLine(JsonConvert.SerializeObject(screenedStocks));
            Console.ReadLine();
        }
Esempio n. 3
0
        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();
        }
Esempio n. 4
0
        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();
        }
Esempio n. 6
0
        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();
        }
Esempio n. 7
0
        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();
        }
Esempio n. 8
0
        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();
        }