├── MANIFEST.in ├── __init__.py ├── nselib ├── debt │ └── __init__.py ├── __init__.py ├── indices │ ├── __init__.py │ ├── index_data.py │ └── config.py ├── derivatives │ ├── __init__.py │ ├── get_func.py │ └── derivative_data.py ├── logger.py ├── capital_market │ ├── __init__.py │ ├── get_func.py │ └── capital_market_data.py ├── constants.py └── libutil.py ├── nselib.egg-info ├── dependency_links.txt ├── top_level.txt ├── requires.txt ├── SOURCES.txt └── PKG-INFO ├── setup.cfg ├── .idea ├── .gitignore ├── vcs.xml ├── inspectionProfiles │ ├── profiles_settings.xml │ └── Project_Default.xml ├── modules.xml ├── misc.xml └── nselib.iml ├── .gitignore ├── requirements.txt ├── setup.py ├── CHANGE_LOG.md ├── README.md └── LICENSE /MANIFEST.in: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /nselib/debt/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /nselib.egg-info/dependency_links.txt: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /nselib.egg-info/top_level.txt: -------------------------------------------------------------------------------- 1 | nselib 2 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description_file = README.md -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | -------------------------------------------------------------------------------- /nselib/__init__.py: -------------------------------------------------------------------------------- 1 | from .libutil import trading_holiday_calendar 2 | 3 | __version__ = 2.3 4 | -------------------------------------------------------------------------------- /nselib.egg-info/requires.txt: -------------------------------------------------------------------------------- 1 | requests 2 | pandas 3 | scipy 4 | pandas_market_calendars 5 | dateutil 6 | -------------------------------------------------------------------------------- /nselib/indices/__init__.py: -------------------------------------------------------------------------------- 1 | from .index_data import index_list, constituent_stock_list, live_index_performances 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # created by virtualenv automatically 2 | venv/ 3 | *.csv 4 | __pycache__/ 5 | *.xml 6 | build/ 7 | dist/ 8 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pandas>=2.0.0 2 | requests>=2.31.0 3 | xlrd>=2.0.1 4 | numpy 5 | dateutil 6 | pandas_market_calendars 7 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 7 | -------------------------------------------------------------------------------- /nselib/derivatives/__init__.py: -------------------------------------------------------------------------------- 1 | from .derivative_data import future_price_volume_data, option_price_volume_data, fno_bhav_copy, \ 2 | participant_wise_open_interest, participant_wise_trading_volume, expiry_dates_future, expiry_dates_option_index,\ 3 | nse_live_option_chain, fii_derivatives_statistics, fno_security_in_ban_period, live_most_active_underlying 4 | -------------------------------------------------------------------------------- /.idea/nselib.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /nselib/logger.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import sys 3 | 4 | 5 | # Create a custom logger 6 | def mylogger(logger): 7 | logger.setLevel(logging.DEBUG) 8 | # Create handlers 9 | c_handler = logging.StreamHandler(sys.stdout) 10 | # Create formatters and add it to handlers 11 | f_format = logging.Formatter('%(name)s::%(levelname)s::%(message)s') 12 | c_handler.setFormatter(f_format) 13 | # Add handlers to the logger 14 | logger.addHandler(c_handler) 15 | return logger 16 | -------------------------------------------------------------------------------- /nselib.egg-info/SOURCES.txt: -------------------------------------------------------------------------------- 1 | LICENSE 2 | MANIFEST.in 3 | README.md 4 | setup.cfg 5 | setup.py 6 | nselib/__init__.py 7 | nselib/constants.py 8 | nselib/libutil.py 9 | nselib/logger.py 10 | nselib.egg-info/PKG-INFO 11 | nselib.egg-info/SOURCES.txt 12 | nselib.egg-info/dependency_links.txt 13 | nselib.egg-info/requires.txt 14 | nselib.egg-info/top_level.txt 15 | nselib/capital_market/__init__.py 16 | nselib/capital_market/capital_market_data.py 17 | nselib/debt/__init__.py 18 | nselib/derivatives/__init__.py 19 | nselib/derivatives/derivative_data.py 20 | nselib/indices/__init__.py 21 | nselib/indices/config.py 22 | nselib/indices/index_data.py -------------------------------------------------------------------------------- /nselib/capital_market/__init__.py: -------------------------------------------------------------------------------- 1 | from .capital_market_data import price_volume_and_deliverable_position_data, price_volume_data, \ 2 | deliverable_position_data, bulk_deal_data, block_deals_data, short_selling_data, \ 3 | bhav_copy_with_delivery, bhav_copy_equities, equity_list, fno_equity_list, fno_index_list, nifty50_equity_list, \ 4 | niftynext50_equity_list, niftymidcap150_equity_list, niftysmallcap250_equity_list, india_vix_data, \ 5 | index_data, market_watch_all_indices, var_begin_day, var_1st_intra_day, var_2nd_intra_day, var_3rd_intra_day, \ 6 | var_4th_intra_day, var_end_of_day, sme_bhav_copy, sme_band_complete, week_52_high_low_report, financial_results_for_equity, \ 7 | corporate_bond_trade_report, bhav_copy_sme, pe_ratio, corporate_actions_for_equity, event_calendar_for_equity, \ 8 | top_gainers_or_losers, most_active_equities, total_traded_stocks 9 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | 3 | with open("README.md", "r") as fh: 4 | long_description = fh.read() 5 | 6 | setuptools.setup( 7 | name='nselib', 8 | packages=setuptools.find_packages(), 9 | version='2.3', 10 | include_package_data=True, 11 | description='library to get NSE India data', 12 | long_description=long_description, 13 | long_description_content_type="text/markdown", 14 | author='Ruchi Tanmay, Amlan Mishra', 15 | author_email='ruchitanmay@gmail.com', 16 | url='https://github.com/RuchiTanmay/nselib', 17 | install_requires=['requests', 'pandas', 'scipy', 'pandas_market_calendars', 'dateutil'], 18 | keywords=['nseindia', 'nse', 'nse data', 'stock data', 'python', 'nse daily data', 'stock markets', 19 | 'nse library', 'nse python', 'nse daily reports'], 20 | classifiers=[ 21 | 'Intended Audience :: Developers', 22 | 'Natural Language :: English', 23 | 'Operating System :: OS Independent', 24 | 'Programming Language :: Python', 25 | 'Programming Language :: Python :: 3', 26 | 'Programming Language :: Python :: Implementation :: PyPy', 27 | 'Topic :: Software Development :: Libraries :: Python Modules' 28 | ], 29 | ) 30 | -------------------------------------------------------------------------------- /nselib/derivatives/get_func.py: -------------------------------------------------------------------------------- 1 | from io import BytesIO, StringIO 2 | import json 3 | from nselib.libutil import * 4 | from nselib.constants import * 5 | 6 | 7 | def get_future_price_volume_data(symbol: str, instrument: str, from_date: str, to_date: str): 8 | origin_url = "https://www.nseindia.com/report-detail/fo_eq_security" 9 | url = "https://www.nseindia.com/api/historical/foCPV?" 10 | payload = f"from={from_date}&to={to_date}&instrumentType={instrument}&symbol={symbol}&csv=true" 11 | try: 12 | data_dict = nse_urlfetch(url + payload, origin_url=origin_url).json() 13 | except Exception as e: 14 | raise ValueError(f" Invalid parameters : NSE error:{e}") 15 | data_df = pd.DataFrame(data_dict['data']).drop(columns='TIMESTAMP') 16 | data_df.columns = cleaning_column_name(data_df.columns) 17 | return data_df[future_price_volume_data_column] 18 | 19 | 20 | def get_option_price_volume_data(symbol: str, instrument: str, option_type: str, from_date: str, to_date: str): 21 | origin_url = "https://www.nseindia.com/report-detail/fo_eq_security" 22 | url = "https://www.nseindia.com/api/historical/foCPV?" 23 | payload = f"from={from_date}&to={to_date}&instrumentType={instrument}&symbol={symbol}" \ 24 | f"&optionType={option_type}&csv=true" 25 | try: 26 | data_dict = nse_urlfetch(url + payload, origin_url=origin_url).json() 27 | except Exception as e: 28 | raise ValueError(f" Invalid parameters : NSE error : {e}") 29 | data_df = pd.DataFrame(data_dict['data']) 30 | if data_df.empty: 31 | raise ValueError(f"Invalid parameters, Please change the parameters") 32 | data_df = data_df.drop(columns='TIMESTAMP') 33 | data_df.columns = cleaning_column_name(data_df.columns) 34 | return data_df[future_price_volume_data_column] 35 | 36 | 37 | def get_nse_option_chain(symbol: str, expiry_date: str): 38 | """ 39 | get NSE option chain for the symbol 40 | :param expiry_date: in 'DD-MMM-YYYY' format eg='25-Dec-2025' 41 | :param symbol: eg:'TCS'/'BANKNIFTY' 42 | :return: pandas dataframe 43 | """ 44 | symbol = cleaning_nse_symbol(symbol) 45 | origin_url = "https://www.nseindia.com/option-chain" 46 | 47 | if any(x in symbol for x in indices_list): 48 | url = f'https://www.nseindia.com/api/option-chain-v3?type=Indices&symbol={symbol}&expiry={expiry_date}' 49 | else: 50 | url = f'https://www.nseindia.com/api/option-chain-v3?type=Equity&symbol={symbol}&expiry={expiry_date}' 51 | payload = nse_urlfetch(url, origin_url=origin_url) 52 | return payload 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /nselib/constants.py: -------------------------------------------------------------------------------- 1 | 2 | dd_mm_yyyy = '%d-%m-%Y' 3 | dd_mmm_yyyy = '%d-%b-%Y' 4 | ddmmyyyy = '%d%m%Y' 5 | ddmmyy = '%d%m%y' 6 | mmm_yy = '%b-%y' 7 | 8 | equity_periods = ['1D', '1W', '1M', '3M', '6M', '1Y'] 9 | indices_list = ['NIFTY', 'FINNIFTY', 'BANKNIFTY'] 10 | 11 | 12 | # ---------- column lists----------------- 13 | 14 | price_volume_and_deliverable_position_data_columns = \ 15 | ['Symbol', 'Series', 'Date', 'PrevClose', 'OpenPrice', 'HighPrice', 16 | 'LowPrice', 'LastPrice', 'ClosePrice', 'AveragePrice', 'TotalTradedQuantity', 17 | 'TurnoverInRs', 'No.ofTrades', 'DeliverableQty', '%DlyQttoTradedQty'] 18 | 19 | price_volume_data_columns = ['Symbol', 'Series', 'Date', 'PrevClose', 'OpenPrice', 'HighPrice', 20 | 'LowPrice', 'LastPrice', 'ClosePrice', 'AveragePrice', 21 | 'TotalTradedQuantity', 'Turnover', 'No.ofTrades'] 22 | 23 | deliverable_data_columns = ['Symbol', 'Series', 'Date', 'TradedQty', 'DeliverableQty', '%DlyQttoTradedQty'] 24 | 25 | bulk_deal_data_columns = ['Date', 'Symbol', 'SecurityName', 'ClientName', 'Buy/Sell', 'QuantityTraded', 26 | 'TradePrice/Wght.Avg.Price', 'Remarks'] 27 | 28 | block_deals_data_columns = ['Date', 'Symbol', 'SecurityName', 'ClientName', 'Buy/Sell', 'QuantityTraded', 29 | 'TradePrice/Wght.Avg.Price', 'Remarks'] 30 | 31 | short_selling_data_columns = ['Date', 'Symbol', 'SecurityName', 'Quantity'] 32 | 33 | bhavcopy_old = ['TradDt', 'ISIN', 'TckrSymb', 'SctySrs', 'OpnPric', 'HghPric', 'LwPric', 'ClsPric', 'LastPric', 34 | 'PrvsClsgPric', 'TtlTradgVol', 'TtlTrfVal', 'TtlNbOfTxsExctd'] 35 | 36 | bhavcopy_new = ['TIMESTAMP', 'ISIN', 'SYMBOL', 'SERIES', 'OPEN', 'HIGH', 'LOW', 'CLOSE', 'LAST', 'PREVCLOSE', 37 | 'TOTTRDQTY', 'TOTTRDVAL', 'TOTALTRADES'] 38 | 39 | future_price_volume_data_column = ['TIMESTAMP', 'INSTRUMENT', 'SYMBOL', 'EXPIRY_DT', 'STRIKE_PRICE', 'OPTION_TYPE', 'MARKET_TYPE', 40 | 'OPENING_PRICE', 'TRADE_HIGH_PRICE', 'TRADE_LOW_PRICE', 'CLOSING_PRICE', 41 | 'LAST_TRADED_PRICE', 'PREV_CLS', 'SETTLE_PRICE', 'TOT_TRADED_QTY', 'TOT_TRADED_VAL', 42 | 'OPEN_INT', 'CHANGE_IN_OI', 'MARKET_LOT', 'UNDERLYING_VALUE'] 43 | 44 | india_vix_data_column = ['TIMESTAMP', 'INDEX_NAME', 'OPEN_INDEX_VAL', 'CLOSE_INDEX_VAL', 'HIGH_INDEX_VAL', 45 | 'LOW_INDEX_VAL', 'PREV_CLOSE', 'VIX_PTS_CHG', 'VIX_PERC_CHG'] 46 | 47 | index_data_columns = ['TIMESTAMP', 'INDEX_NAME', 'OPEN_INDEX_VAL', 'HIGH_INDEX_VAL', 'CLOSE_INDEX_VAL', 48 | 'LOW_INDEX_VAL', 'TRADED_QTY', 'TURN_OVER'] 49 | 50 | var_columns = ['RecordType', 'Symbol', 'Series', 'Isin', 'SecurityVaR', 'IndexVaR', 'VaRMargin', 51 | 'ExtremeLossRate', 'AdhocMargin', 'ApplicableMarginRate'] 52 | -------------------------------------------------------------------------------- /CHANGE_LOG.md: -------------------------------------------------------------------------------- 1 | # CHANGE LOG 2 | #### All the changes are listed... 3 | ### Version: 2.3 [12/12/2025] 4 | * functions added top_gainers_or_losers, most_active_equities, total_traded_stocks in capital market section 5 | * functions added live_most_active_underlying in derivative section 6 | * functions added live_index_performances in indices section 7 | 8 | ### Version: 2.2 [10/12/2025] 9 | * nse_live_option_chain issue fix 10 | 11 | ### Version: 2.1 [06/12/2025] 12 | * added indices section data in nselib 13 | * functions added get_index_list to get the available NSE indices for each category of indices 14 | * functions added get_constituent_stock_list to get list of all that stocks constituent . 15 | 16 | ### Version: 2.0 [12/08/2025] 17 | * functions added corporate_actions_for_equity to get corporate actions information from trading for the date 18 | * functions added event_calendar_for_equity to get event calendar 19 | * removed internal loggings 20 | 21 | ### Version: 1.9 [18/05/2025] 22 | * functions added corporate_bond_trade_report to get NSE corporate bond trade report as per the traded date 23 | * functions added bhav_copy_sme to get bhav copy for SME data as per the traded date 24 | * functions added pe_ratio to get pe ratio for all NSE equities 25 | 26 | ### Version: 1.8 [26/03/2025] 27 | * functions added fno_security_in_ban_period to get securities baned from trading for the date 28 | 29 | ### Version: 1.7 [16/03/2025] 30 | * functions added financial_results_for_equity to get financial results 31 | 32 | ### Version: 1.6 [23/02/2025] 33 | * functions added to capital market (fno_index_list) 34 | * Issue fix with fetching previous day if holiday 35 | * trading_holiday_calendar issue fixed 36 | 37 | ### Version: 1.5 [04/11/2024] 38 | * index_data function issue fixes 39 | 40 | ### Version: 1.4 [20/10/2024] 41 | * major nseindia api fixes 42 | 43 | ### Version: 1.3 [15/10/2024] 44 | * nseindia api fixes 45 | 46 | ### Version: 1.2 [23/09/2024] 47 | * nseindia data path changed 48 | 49 | ### Version: 1.1 [16/09/2024] 50 | * functions added to capital market (var_begin_day, var_1st_intra_day, var_2nd_intra_day, var_3rd_intra_day, var_4th_intra_day, var_end_of_day, sme_bhav_copy, sme_band_complete, week_52_high_low_report) 51 | 52 | ### Version: 1.0 [09/07/2024] 53 | * Code changes as per new NSE data changes. fixes all bugs 54 | 55 | ### Version: 0.7 [30/07/2023] 56 | * Now we can get the Derivative bhav copy from 2008 on wards 57 | 58 | ### Version: 0.6 [02/07/2023] 59 | * Functions added (market_watch_all_indices, fii_dii_trading_activity) 60 | 61 | ### Version: 0.5 [24/06/2023] 62 | * Functions added (india_vix_data, index_data, expiry_dates_future, expiry_dates_option_index, nse_live_option_chain, fii_derivatives_statistics) 63 | 64 | ### Version: 0.4 [20/06/2023] 65 | * Functions added (equity_list, fno_equity_list, nifty50_equity_list) 66 | 67 | ### Version: 0.3 [19/06/2023] 68 | * Issue Fixes 69 | 70 | ### Version: 0.2 [19/06/2023] 71 | * Library's first look published 72 | 73 | ### Version: 0.1 [17/06/2023] 74 | * Initial structure of the library published 75 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 64 | -------------------------------------------------------------------------------- /nselib/indices/index_data.py: -------------------------------------------------------------------------------- 1 | from io import BytesIO 2 | from nselib.libutil import * 3 | import config as conf 4 | import pandas as pd 5 | 6 | 7 | def get_class(index_category: str): 8 | category = f"Nifty{index_category}" 9 | category_class = getattr(conf, category, None) 10 | 11 | if category_class is None: 12 | raise ValueError(f"No such category in config: {category}") 13 | return category_class 14 | 15 | 16 | def index_list(index_category: str = 'BroadMarketIndices'): 17 | """ 18 | to get the available NSE indices for each category of indices. there ar 4 category defined by NSE link as below 19 | https://www.nseindia.com/static/products-services/about-indices.. 20 | :param index_category: SectoralIndices/ BroadMarketIndices/ ThematicIndices/ StrategyIndices 21 | :return: list 22 | """ 23 | return get_class(index_category).indices_list 24 | 25 | 26 | def validate_index_category(index_category: str = 'BroadMarketIndices'): 27 | category_list = ['SectoralIndices', 'BroadMarketIndices', 'ThematicIndices', 'StrategyIndices'] 28 | if index_category in category_list: 29 | pass 30 | else: 31 | raise ValueError(f'{index_category} is not a valid index_category:: please select category_list from list : {category_list}') 32 | 33 | 34 | def validate_index_name(index_category: str = 'BroadMarketIndices', index_name: str = 'Nifty 50'): 35 | validate_index_category(index_category) 36 | ind_list = index_list(index_category) 37 | if index_name in ind_list: 38 | pass 39 | else: 40 | raise ValueError(f'{index_name} is not a valid index_name:: please select index name from list : {ind_list}') 41 | 42 | 43 | def constituent_stock_list(index_category: str = 'BroadMarketIndices', index_name: str = 'Nifty 50'): 44 | """ 45 | to get list of all that stocks constituent with the given index and index_category. 46 | :param index_category: SectoralIndices/ BroadMarketIndices/ ThematicIndices/ StrategyIndices 47 | :param index_name: select name of index from the index list provided by get_index_list 48 | :return: pandas.DataFrame 49 | :raise ValueError if the parameter input is not proper 50 | """ 51 | validate_index_name(index_category, index_name) 52 | url = get_class(index_category).index_constituent_list_urls[index_name] 53 | if not url: 54 | raise FileNotFoundError(f' Data not found for index {index_name}') 55 | response = nse_urlfetch(url) 56 | if response.status_code == 200: 57 | stocks_df = pd.read_csv(BytesIO(response.content)) 58 | else: 59 | raise FileNotFoundError(f' Data not found, check index_name or index_category ...') 60 | url_fs = get_class(index_category).index_factsheet_urls[index_name] 61 | print(f" Note: For more detail information related to {index_name} Please check the Fact Sheet - {url_fs}") 62 | return stocks_df 63 | 64 | 65 | def live_index_performances(): 66 | """ 67 | to get index performances in live market, after market hour it will get as per last traded value 68 | link : https://www.nseindia.com/market-data/index-performances 69 | :return: 70 | """ 71 | origin_url = "https://www.nseindia.com/market-data/index-performances" 72 | url = f"https://www.nseindia.com/api/allIndices" 73 | try: 74 | data_json = nse_urlfetch(url, origin_url=origin_url).json() 75 | data_df = pd.DataFrame(data_json['data']) 76 | except Exception as e: 77 | raise NSEdataNotFound(f" Resource not available MSG: {e}") 78 | data_df.drop(columns=['chartTodayPath', 'chart30dPath', 'chart365dPath'], inplace=True) 79 | return data_df 80 | 81 | 82 | # if __name__ == '__main__': 83 | 84 | # data = constituent_stock_list(index_category='BroadMarketIndices', index_name='Nifty 50') 85 | # data = live_index_performances() 86 | # print(data) 87 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NSElib 2.3 2 | 3 | Python Library to get publicly available data on new NSE india website. 4 | 5 | Release Notes 6 | * Compatible and Tested with Python 3.8 and above 7 | * Future release will be done on requirement basic 8 | 9 | ## Libraries Required 10 | - requests 11 | - beautifulsoup 12 | - numpy 13 | - scipy 14 | - pandas 15 | - lxml 16 | - pandas_market_calendars 17 | 18 | For Windows systems you can install Anaconda, this will cover many dependencies (You'll have to install requests and beautifulsoup additionally though) 19 | 20 | ## Installation 21 | Fresh installation 22 | 23 | ```$pip install nselib``` 24 | 25 | Upgrade 26 | 27 | ```$pip install nselib --upgrade``` 28 | 29 | ## Function list 30 | 31 | ### nselib 32 | * trading_holiday_calendar 33 | 34 | Example : 35 | 36 | import nselib 37 | 38 | data = nselib.trading_holiday_calendar() 39 | 40 | ### Capital Market 41 | * price_volume_and_deliverable_position_data 42 | * price_volume_data 43 | * deliverable_position_data 44 | * bulk_deal_data 45 | * block_deals_data 46 | * short_selling_data 47 | * bhav_copy_with_delivery 48 | * bhav_copy_equities 49 | * equity_list 50 | * fno_equity_list 51 | * fno_index_list 52 | * nifty50_equity_list 53 | * niftynext50_equity_list 54 | * niftymidcap150_equity_list 55 | * niftysmallcap250_equity_list 56 | * india_vix_data 57 | * index_data 58 | * market_watch_all_indices 59 | * fii_dii_trading_activity 60 | * var_begin_day 61 | * var_1st_intra_day 62 | * var_2nd_intra_day 63 | * var_3rd_intra_day 64 | * var_4th_intra_day 65 | * var_end_of_day 66 | * sme_bhav_copy 67 | * sme_band_complete 68 | * week_52_high_low_report 69 | * financial_results_for_equity 70 | * corporate_bond_trade_report 71 | * bhav_copy_sme 72 | * pe_ratio 73 | * corporate_actions_for_equity 74 | * event_calendar_for_equity 75 | * top_gainers_or_losers 76 | * most_active_equities 77 | * total_traded_stocks 78 | 79 | Example : 80 | 81 | from nselib import capital_market 82 | 83 | data = capital_market.price_volume_and_deliverable_position_data(symbol='SBIN', from_date='20-06-2023', to_date='20-07-2023') 84 | 85 | OR 86 | 87 | data = capital_market.price_volume_and_deliverable_position_data(symbol='SBIN', period='1M') 88 | 89 | data = capital_market.bhav_copy_with_delivery(trade_date='20-06-2024') 90 | 91 | More functions will be available in future releases... 92 | 93 | ### Derivative 94 | * future_price_volume_data 95 | * option_price_volume_data 96 | * fno_bhav_copy 97 | * participant_wise_open_interest 98 | * participant_wise_trading_volume 99 | * expiry_dates_future 100 | * expiry_dates_option_index 101 | * nse_live_option_chain 102 | * fii_derivatives_statistics 103 | * fno_security_in_ban_period 104 | * live_most_active_underlying 105 | 106 | Example : 107 | 108 | from nselib import derivatives 109 | 110 | data = derivatives.future_price_volume_data(symbol='SBIN', instrument='FUTSTK', from_date='20-06-2023', to_date='20-07-2023') 111 | 112 | OR 113 | 114 | data = derivatives.price_volume_and_deliverable_position_data(symbol='BANKNIFTY', instrument='FUTIDX', period='1M') 115 | 116 | Note: instrument type ( future index = FUTIDX, future stocks = FUTSTK, option index = OPTIDX, option stocks = OPTSTK) 117 | 118 | More functions will be available in future releases... 119 | 120 | ### Indices 121 | * index_list 122 | * constituent_stock_list 123 | * live_index_performances 124 | 125 | Example : 126 | 127 | from nselib import indices 128 | 129 | data = indices.constituent_stock_list(index_category='BroadMarketIndices', index_name='Nifty 50') 130 | 131 | More functions will be available in future releases... 132 | 133 | ### Debt 134 | 135 | More functions will be available in future releases... 136 | 137 | 138 | ## How can I contribute? 139 | There are multiple ways in which you can contribute- 140 | 141 | ### Write about your project 142 | 143 | There are working on to add many function to this library. NSElib at the moment is short of good documentation. There are a lot of features in NSElib yet to come :( , so till we complete the documentation, I'll need support from the community. 144 | 145 | Please write about your projects in blogs, quora answers and other forums, so that people find working examples to get started. 146 | 147 | ### Raising issues, bugs, enhancement requests 148 | 149 | For quick resolution please raise issues both [here on issue page](https://github.com/RuchiTanmay/nselib/issues). I'll try my best to address the issues quickly on github as and when I get notified, but raising it on stackoverflow will provide you access to a larger group and someone else might solve your problem before I do. 150 | 151 | ### Contact author on [LinkedIn](https://www.linkedin.com/in/ruchi-tanmay-61848219) 152 | 153 | ### Submit patches 154 | 155 | If you have fixed an issue or added a new feature, please fork this repository, make your changes and submit a pull request. [Here's good article on how to do this.](https://code.tutsplus.com/tutorials/how-to-collaborate-on-github--net-34267) 156 | 157 | Looking forward for healthy participation from community. 158 | -------------------------------------------------------------------------------- /nselib.egg-info/PKG-INFO: -------------------------------------------------------------------------------- 1 | Metadata-Version: 2.1 2 | Name: nselib 3 | Version: 2.2 4 | Summary: library to get NSE India data 5 | Home-page: https://github.com/RuchiTanmay/nselib 6 | Author: Ruchi Tanmay, Amlan Mishra 7 | Author-email: ruchitanmay@gmail.com 8 | License: UNKNOWN 9 | Keywords: nseindia,nse,nse data,stock data,python,nse daily data,stock markets,nse library,nse python,nse daily reports 10 | Platform: UNKNOWN 11 | Classifier: Intended Audience :: Developers 12 | Classifier: Natural Language :: English 13 | Classifier: Operating System :: OS Independent 14 | Classifier: Programming Language :: Python 15 | Classifier: Programming Language :: Python :: 3 16 | Classifier: Programming Language :: Python :: Implementation :: PyPy 17 | Classifier: Topic :: Software Development :: Libraries :: Python Modules 18 | Description-Content-Type: text/markdown 19 | License-File: LICENSE 20 | 21 | # NSElib 2.2 22 | 23 | Python Library to get publicly available data on new NSE india website. 24 | 25 | Release Notes 26 | * Compatible and Tested with Python 3.8 and above 27 | * Future release will be done on requirement basic 28 | 29 | ## Libraries Required 30 | - requests 31 | - beautifulsoup 32 | - numpy 33 | - scipy 34 | - pandas 35 | - lxml 36 | - pandas_market_calendars 37 | 38 | For Windows systems you can install Anaconda, this will cover many dependencies (You'll have to install requests and beautifulsoup additionally though) 39 | 40 | ## Installation 41 | Fresh installation 42 | 43 | ```$pip install nselib``` 44 | 45 | Upgrade 46 | 47 | ```$pip install nselib --upgrade``` 48 | 49 | ## Function list 50 | 51 | ### nselib 52 | * trading_holiday_calendar 53 | 54 | Example : 55 | 56 | import nselib 57 | 58 | data = nselib.trading_holiday_calendar() 59 | 60 | ### Capital Market 61 | * price_volume_and_deliverable_position_data 62 | * price_volume_data 63 | * deliverable_position_data 64 | * bulk_deal_data 65 | * block_deals_data 66 | * short_selling_data 67 | * bhav_copy_with_delivery 68 | * bhav_copy_equities 69 | * equity_list 70 | * fno_equity_list 71 | * fno_index_list 72 | * nifty50_equity_list 73 | * niftynext50_equity_list 74 | * niftymidcap150_equity_list 75 | * niftysmallcap250_equity_list 76 | * india_vix_data 77 | * index_data 78 | * market_watch_all_indices 79 | * fii_dii_trading_activity 80 | * var_begin_day 81 | * var_1st_intra_day 82 | * var_2nd_intra_day 83 | * var_3rd_intra_day 84 | * var_4th_intra_day 85 | * var_end_of_day 86 | * sme_bhav_copy 87 | * sme_band_complete 88 | * week_52_high_low_report 89 | * financial_results_for_equity 90 | * corporate_bond_trade_report 91 | * bhav_copy_sme 92 | * pe_ratio 93 | * corporate_actions_for_equity 94 | * event_calendar_for_equity 95 | 96 | Example : 97 | 98 | from nselib import capital_market 99 | 100 | data = capital_market.price_volume_and_deliverable_position_data(symbol='SBIN', from_date='20-06-2023', to_date='20-07-2023') 101 | 102 | OR 103 | 104 | data = capital_market.price_volume_and_deliverable_position_data(symbol='SBIN', period='1M') 105 | 106 | data = capital_market.bhav_copy_with_delivery(trade_date='20-06-2024') 107 | 108 | More functions will be available in future releases... 109 | 110 | ### Derivative 111 | * future_price_volume_data 112 | * option_price_volume_data 113 | * fno_bhav_copy 114 | * participant_wise_open_interest 115 | * participant_wise_trading_volume 116 | * expiry_dates_future 117 | * expiry_dates_option_index 118 | * nse_live_option_chain 119 | * fii_derivatives_statistics 120 | * fno_security_in_ban_period 121 | 122 | Example : 123 | 124 | from nselib import derivatives 125 | 126 | data = derivatives.future_price_volume_data(symbol='SBIN', instrument='FUTSTK', from_date='20-06-2023', to_date='20-07-2023') 127 | 128 | OR 129 | 130 | data = derivatives.price_volume_and_deliverable_position_data(symbol='BANKNIFTY', instrument='FUTIDX', period='1M') 131 | 132 | Note: instrument type ( future index = FUTIDX, future stocks = FUTSTK, option index = OPTIDX, option stocks = OPTSTK) 133 | 134 | More functions will be available in future releases... 135 | 136 | ### Indices 137 | * index_list 138 | * constituent_stock_list 139 | 140 | Example : 141 | 142 | from nselib import indices 143 | 144 | data = indices.constituent_stock_list(index_category='BroadMarketIndices', index_name='Nifty 50') 145 | 146 | More functions will be available in future releases... 147 | 148 | ### Debt 149 | 150 | More functions will be available in future releases... 151 | 152 | 153 | ## How can I contribute? 154 | There are multiple ways in which you can contribute- 155 | 156 | ### Write about your project 157 | 158 | There are working on to add many function to this library. NSElib at the moment is short of good documentation. There are a lot of features in NSElib yet to come :( , so till we complete the documentation, I'll need support from the community. 159 | 160 | Please write about your projects in blogs, quora answers and other forums, so that people find working examples to get started. 161 | 162 | ### Raising issues, bugs, enhancement requests 163 | 164 | For quick resolution please raise issues both [here on issue page](https://github.com/RuchiTanmay/nselib/issues). I'll try my best to address the issues quickly on github as and when I get notified, but raising it on stackoverflow will provide you access to a larger group and someone else might solve your problem before I do. 165 | 166 | ### Contact author on [LinkedIn](https://www.linkedin.com/in/ruchi-tanmay-61848219) 167 | 168 | ### Submit patches 169 | 170 | If you have fixed an issue or added a new feature, please fork this repository, make your changes and submit a pull request. [Here's good article on how to do this.](https://code.tutsplus.com/tutorials/how-to-collaborate-on-github--net-34267) 171 | 172 | Looking forward for healthy participation from community. 173 | 174 | 175 | -------------------------------------------------------------------------------- /nselib/libutil.py: -------------------------------------------------------------------------------- 1 | import os 2 | from datetime import datetime, timedelta, date 3 | import requests 4 | import numpy as np 5 | # from dateutil.relativedelta import relativedelta 6 | import pandas as pd 7 | from nselib.constants import * 8 | import pandas_market_calendars as mcal 9 | 10 | default_header = { 11 | "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36" 12 | } 13 | 14 | header = { 15 | "referer": "https://www.nseindia.com/", 16 | "Connection": "keep-alive", 17 | "Cache-Control": "max-age=0", 18 | "DNT": "1", 19 | "Upgrade-Insecure-Requests": "1", 20 | "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36", 21 | "Sec-Fetch-User": "?1", 22 | "Accept": "ext/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7", 23 | "Sec-Fetch-Site": "none", 24 | "Sec-Fetch-Mode": "navigate", 25 | "Accept-Language": "en-US,en;q=0.9,hi;q=0.8" 26 | } 27 | 28 | nse_calendar = mcal.get_calendar("NSE") 29 | 30 | 31 | class CalenderNotFound(Exception): 32 | def __init__(self, message): 33 | 34 | # Call the base class constructor with the parameters it needs 35 | super(CalenderNotFound, self).__init__(message) 36 | 37 | 38 | class NSEdataNotFound(Exception): 39 | def __init__(self, message): 40 | super(NSEdataNotFound, self).__init__(message) 41 | 42 | 43 | def validate_param_from_list(value: str, static_options_list: list): 44 | if value not in static_options_list: 45 | raise ValueError(f"'{value}' not a valid parameter :: select from {static_options_list}") 46 | else: 47 | pass 48 | 49 | 50 | def validate_date_param(from_date: str, to_date: str, period: str): 51 | if not period and (not from_date or not to_date): 52 | raise ValueError(' Please provide the valid parameters') 53 | elif period and period.upper() not in equity_periods: 54 | raise ValueError(f'period = {period} is not a valid value') 55 | 56 | try: 57 | if not period: 58 | from_date = datetime.strptime(from_date, dd_mm_yyyy) 59 | to_date = datetime.strptime(to_date, dd_mm_yyyy) 60 | time_delta = (to_date - from_date).days 61 | if time_delta < 1: 62 | raise ValueError(f'to_date should greater than from_date ') 63 | except Exception as e: 64 | print(e) 65 | raise ValueError(f'either or both from_date = {from_date} || to_date = {to_date} are not valid value') 66 | 67 | 68 | def subtract_months(dt, months): 69 | # calculate target year and month 70 | year = dt.year 71 | month = dt.month - months 72 | 73 | # adjust year and month when month < 1 74 | while month <= 0: 75 | month += 12 76 | year -= 1 77 | 78 | # maximum days in each month 79 | month_days = [31, 80 | 29 if (year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)) else 28, 81 | 31, 30, 31, 30, 82 | 31, 31, 30, 31, 30, 31] 83 | 84 | # adjust the day if current date > max days in target month 85 | day = min(dt.day, month_days[month - 1]) 86 | 87 | return date(year, month, day) 88 | 89 | 90 | def derive_from_and_to_date(from_date: str = None, to_date: str = None, period: str = None): 91 | if not period: 92 | return from_date, to_date 93 | today = date.today() 94 | conditions = [period.upper() == '1D', 95 | period.upper() == '1W', 96 | period.upper() == '1M', 97 | period.upper() == '6M', 98 | period.upper() == '1Y' 99 | ] 100 | value = [today - timedelta(days=1), 101 | today - timedelta(weeks=1), 102 | subtract_months(today, 1), 103 | subtract_months(today, 6), 104 | subtract_months(today, 12)] 105 | 106 | f_date = np.select(conditions, value, default=(today - timedelta(days=1))) 107 | f_date = pd.to_datetime(str(f_date)) 108 | while True: 109 | date_chk = nse_calendar.schedule(start_date=f_date, end_date=f_date) 110 | if not date_chk.empty: # If market was open on this day 111 | break # Stop the loop 112 | f_date -= timedelta(days=1) 113 | from_date = f_date.strftime(dd_mm_yyyy) 114 | today = today.strftime(dd_mm_yyyy) 115 | return from_date, today 116 | 117 | 118 | def cleaning_column_name(col:list): 119 | unwanted_str_list = ['FH_', 'EOD_', 'HIT_'] 120 | new_col = col 121 | for unwanted in unwanted_str_list: 122 | new_col = [name.replace(f'{unwanted}', '') for name in new_col] 123 | return new_col 124 | 125 | 126 | def cleaning_nse_symbol(symbol): 127 | symbol = symbol.replace('&', '%26') # URL Parse for Stocks Like M&M Finance 128 | return symbol.upper() 129 | 130 | 131 | def nse_urlfetch(url, origin_url="http://nseindia.com"): 132 | r_session = requests.session() 133 | nse_live = r_session.get(origin_url, headers=default_header) 134 | cookies = nse_live.cookies 135 | return r_session.get(url, headers=header, cookies=cookies) 136 | 137 | 138 | def get_nselib_path(): 139 | """ 140 | Extract isap file path 141 | """ 142 | mydir = os.getcwd() 143 | return mydir.split(r'\nselib', 1)[0] 144 | 145 | 146 | def trading_holiday_calendar(): 147 | data_df = pd.DataFrame(columns=['Product', 'tradingDate', 'weekDay', 'description', 'Sr_no']) 148 | url = "https://www.nseindia.com/api/holiday-master?type=trading" 149 | try: 150 | data_dict = nse_urlfetch(url).json() 151 | except Exception as e: 152 | raise CalenderNotFound(" Calender data Not found try after some time ") 153 | for prod in data_dict: 154 | h_df = pd.DataFrame(data_dict[prod]) 155 | h_df['Product'] = prod 156 | data_df = pd.concat([data_df, h_df]) 157 | condition = [data_df['Product'] == 'CBM', data_df['Product'] == 'CD', data_df['Product'] == 'CM', 158 | data_df['Product'] == 'CMOT', data_df['Product'] == 'COM', data_df['Product'] == 'FO', 159 | data_df['Product'] == 'IRD', data_df['Product'] == 'MF', data_df['Product'] == 'NDM', 160 | data_df['Product'] == 'NTRP', data_df['Product'] == 'SLBS'] 161 | value = ['Corporate Bonds', 'Currency Derivatives', 'Equities', 'CMOT', 'Commodity Derivatives', 'Equity Derivatives', 162 | 'Interest Rate Derivatives', 'Mutual Funds', 'New Debt Segment', 'Negotiated Trade Reporting Platform', 163 | 'Securities Lending & Borrowing Schemes'] 164 | data_df['Product'] = np.select(condition, value, default='Unknown') 165 | return data_df 166 | 167 | 168 | if __name__ == '__main__': 169 | # data = derive_from_and_to_date('6M') 170 | print(trading_holiday_calendar()) 171 | 172 | 173 | 174 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /nselib/capital_market/get_func.py: -------------------------------------------------------------------------------- 1 | from io import BytesIO, StringIO 2 | import json 3 | from nselib.libutil import * 4 | from nselib.constants import * 5 | 6 | 7 | def get_price_volume_and_deliverable_position_data(symbol: str, from_date: str, to_date: str): 8 | origin_url = "https://nsewebsite-staging.nseindia.com/report-detail/eq_security" 9 | url = "https://www.nseindia.com/api/historicalOR/generateSecurityWiseHistoricalData?" 10 | payload = f"from={from_date}&to={to_date}&symbol={symbol}&type=priceVolumeDeliverable&series=ALL&csv=true" 11 | try: 12 | data_text = nse_urlfetch(url + payload, origin_url=origin_url).text 13 | data_text = data_text.replace('\x82', '').replace('â¹', 'In Rs') 14 | with open('file.csv', 'w') as f: 15 | f.write(data_text) 16 | f.close() 17 | except Exception as e: 18 | raise NSEdataNotFound(f" Resource not available MSG: {e}") 19 | data_df = pd.read_csv('file.csv') 20 | data_df.columns = [name.replace(' ', '') for name in data_df.columns] 21 | return data_df 22 | 23 | 24 | def get_price_volume_data(symbol: str, from_date: str, to_date: str): 25 | origin_url = "https://nsewebsite-staging.nseindia.com/report-detail/eq_security" 26 | url = "https://www.nseindia.com/api/historicalOR/generateSecurityWiseHistoricalData?" 27 | payload = f"from={from_date}&to={to_date}&symbol={symbol}&type=priceVolume&series=ALL&csv=true" 28 | try: 29 | data_text = nse_urlfetch(url + payload, origin_url=origin_url) 30 | if data_text.status_code != 200: 31 | raise NSEdataNotFound(f" Resource not available for Price Volume Data") 32 | except Exception as e: 33 | raise NSEdataNotFound(f" Resource not available MSG: {e}") 34 | data_df = pd.read_csv(BytesIO(data_text.content), index_col=False) 35 | data_df.columns = [name.replace(' ', '') for name in data_df.columns] 36 | return data_df 37 | 38 | 39 | def get_deliverable_position_data(symbol: str, from_date: str, to_date: str): 40 | origin_url = "https://nsewebsite-staging.nseindia.com/report-detail/eq_security" 41 | url = "https://www.nseindia.com/api/historicalOR/generateSecurityWiseHistoricalData?" 42 | payload = f"from={from_date}&to={to_date}&symbol={symbol}&type=deliverable&series=ALL&csv=true" 43 | try: 44 | data_text = nse_urlfetch(url + payload, origin_url=origin_url) 45 | if data_text.status_code != 200: 46 | raise NSEdataNotFound(f" Resource not available for deliverable_position_data") 47 | except Exception as e: 48 | raise NSEdataNotFound(f" Resource not available MSG: {e}") 49 | data_df = pd.read_csv(BytesIO(data_text.content), index_col=False) 50 | data_df.columns = [name.replace(' ', '') for name in data_df.columns] 51 | return data_df 52 | 53 | 54 | def get_india_vix_data(from_date: str, to_date: str): 55 | origin_url = "https://nsewebsite-staging.nseindia.com/report-detail/eq_security" 56 | url = f"https://www.nseindia.com/api/historicalOR/vixhistory?from={from_date}&to={to_date}&csv=true" 57 | try: 58 | data_json = nse_urlfetch(url, origin_url=origin_url).json() 59 | data_df = pd.DataFrame(data_json['data']) 60 | except Exception as e: 61 | raise NSEdataNotFound(f" Resource not available MSG: {e}") 62 | # data_df.drop(columns='TIMESTAMP', inplace=True) 63 | data_df.columns = cleaning_column_name(data_df.columns) 64 | return data_df[india_vix_data_column] 65 | 66 | 67 | def get_index_data(index: str, from_date: str, to_date: str): 68 | index = index.replace(' ', '%20').upper() 69 | origin_url = "https://www.nseindia.com/reports-indices-historical-index-data" 70 | url = f"https://www.nseindia.com/api/historical/indicesHistory?indexType={index}&from={from_date}&to={to_date}" 71 | try: 72 | data_json = nse_urlfetch(url, origin_url=origin_url).json() 73 | data_close_df = pd.DataFrame(data_json['data']['indexCloseOnlineRecords']).drop(columns=['_id', "EOD_TIMESTAMP"]) 74 | data_turnover_df = pd.DataFrame(data_json['data']['indexTurnoverRecords']).drop(columns=['_id', 75 | 'HIT_INDEX_NAME_UPPER']) 76 | data_df = pd.merge(data_close_df,data_turnover_df, on='TIMESTAMP', how='inner') 77 | except Exception as e: 78 | raise NSEdataNotFound(f" Resource not available MSG: {e}") 79 | data_df.drop(columns='TIMESTAMP', inplace=True) 80 | data_df.columns = cleaning_column_name(data_df.columns) 81 | return data_df[index_data_columns] 82 | 83 | 84 | def get_bulk_deal_data(from_date: str, to_date: str): 85 | # print(from_date, to_date) 86 | origin_url = "https://nsewebsite-staging.nseindia.com" 87 | url = "https://www.nseindia.com/api/historicalOR/bulk-block-short-deals?optionType=bulk_deals&" 88 | payload = f"from={from_date}&to={to_date}&csv=true" 89 | # print(url + payload) 90 | data_text = nse_urlfetch(url + payload, origin_url=origin_url) 91 | if data_text.status_code != 200: 92 | raise NSEdataNotFound(f" Resource not available for bulk_deal_data") 93 | data_df = pd.read_csv(BytesIO(data_text.content), index_col=False) 94 | data_df.columns = [name.replace(' ', '') for name in data_df.columns] 95 | return data_df 96 | 97 | 98 | def get_block_deals_data(from_date: str, to_date: str): 99 | # print(from_date, to_date) 100 | origin_url = "https://nsewebsite-staging.nseindia.com" 101 | url = "https://www.nseindia.com/api/historicalOR/bulk-block-short-deals?optionType=block_deals&" 102 | payload = f"from={from_date}&to={to_date}&csv=true" 103 | data_text = nse_urlfetch(url + payload, origin_url=origin_url) 104 | if data_text.status_code != 200: 105 | raise NSEdataNotFound(f" Resource not available for block_deals_data") 106 | data_df = pd.read_csv(BytesIO(data_text.content), index_col=False) 107 | data_df.columns = [name.replace(' ', '') for name in data_df.columns] 108 | return data_df 109 | 110 | 111 | def get_short_selling_data(from_date: str, to_date: str): 112 | """ 113 | NSE short selling data in data frame 114 | :param from_date: 115 | :param to_date: 116 | :return: 117 | """ 118 | # print(from_date, to_date) 119 | origin_url = "https://nsewebsite-staging.nseindia.com" 120 | url = "https://www.nseindia.com/api/historicalOR/bulk-block-short-deals?optionType=short_selling&" 121 | payload = f"from={from_date}&to={to_date}&csv=true" 122 | data_text = nse_urlfetch(url + payload,origin_url=origin_url) 123 | if data_text.status_code != 200: 124 | raise NSEdataNotFound(f" Resource not available for short_selling_data") 125 | data_df = pd.read_csv(BytesIO(data_text.content), index_col=False) 126 | data_df.columns = [name.replace(' ', '') for name in data_df.columns] 127 | return data_df 128 | 129 | 130 | def get_financial_results_master(from_date: str = None, 131 | to_date: str = None, 132 | period: str = None, 133 | fo_sec: bool = False, 134 | fin_period: str = 'Quarterly'): 135 | validate_date_param(from_date, to_date, period) 136 | from_date, to_date = derive_from_and_to_date(from_date=from_date, to_date=to_date, period=period) 137 | origin_url = "https://www.nseindia.com/companies-listing/corporate-filings-financial-results" 138 | url_ = "https://www.nseindia.com/api/corporates-financial-results?index=equities&" 139 | if fo_sec: 140 | payload = f'from_date={from_date}&to_date={to_date}&fo_sec=true&period={fin_period}' 141 | else: 142 | payload = f'from_date={from_date}&to_date={to_date}&period={fin_period}' 143 | data_text = nse_urlfetch(url_ + payload, origin_url=origin_url) 144 | if data_text.status_code != 200: 145 | raise NSEdataNotFound(f" Resource not available for financial data with these parameters") 146 | json_str = data_text.content.decode("utf-8") 147 | data_list = json.loads(json_str) 148 | master_data_df = pd.DataFrame(data_list) 149 | master_data_df.columns = [name.replace(' ', '') for name in master_data_df.columns] 150 | headers = { 151 | 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3', 152 | 'Accept': '*/*', 153 | 'Accept-Language': 'en-US,en;q=0.9', 154 | 'Referer': 'https://www.nseindia.com/' 155 | } 156 | ns = { 157 | "xbrli": "http://www.xbrl.org/2003/instance", 158 | "in-bse-fin": "http://www.bseindia.com/xbrl/fin/2020-03-31/in-bse-fin" 159 | } 160 | keys_to_extract = [ 161 | "ScripCode", "Symbol", "MSEISymbol", "NameOfTheCompany", "ClassOfSecurity", 162 | "DateOfStartOfFinancialYear", "DateOfEndOfFinancialYear", 163 | "DateOfBoardMeetingWhenFinancialResultsWereApproved", 164 | "DateOnWhichPriorIntimationOfTheMeetingForConsideringFinancialResultsWasInformedToTheExchange", 165 | "DescriptionOfPresentationCurrency", "LevelOfRoundingUsedInFinancialStatements", 166 | "ReportingQuarter", "StartTimeOfBoardMeeting", "EndTimeOfBoardMeeting", 167 | "DateOfStartOfBoardMeeting", "DateOfEndOfBoardMeeting", 168 | "DeclarationOfUnmodifiedOpinionOrStatementOnImpactOfAuditQualification", 169 | "IsCompanyReportingMultisegmentOrSingleSegment", "DescriptionOfSingleSegment", 170 | "DateOfStartOfReportingPeriod", "DateOfEndOfReportingPeriod", 171 | "WhetherResultsAreAuditedOrUnaudited", "NatureOfReportStandaloneConsolidated", 172 | "RevenueFromOperations", "OtherIncome", "Income", "CostOfMaterialsConsumed", 173 | "PurchasesOfStockInTrade", "ChangesInInventoriesOfFinishedGoodsWorkInProgressAndStockInTrade", 174 | "EmployeeBenefitExpense", "FinanceCosts", "DepreciationDepletionAndAmortisationExpense", 175 | "OtherExpenses", "Expenses", "ProfitBeforeExceptionalItemsAndTax", "ExceptionalItemsBeforeTax", 176 | "ProfitBeforeTax", "CurrentTax", "DeferredTax", "TaxExpense", 177 | "NetMovementInRegulatoryDeferralAccountBalancesRelatedToProfitOrLossAndTheRelatedDeferredTaxMovement", 178 | "ProfitLossForPeriodFromContinuingOperations", "ProfitLossFromDiscontinuedOperationsBeforeTax", 179 | "TaxExpenseOfDiscontinuedOperations", "ProfitLossFromDiscontinuedOperationsAfterTax", 180 | "ShareOfProfitLossOfAssociatesAndJointVenturesAccountedForUsingEquityMethod", 181 | "ProfitLossForPeriod", "OtherComprehensiveIncomeNetOfTaxes", 182 | "ComprehensiveIncomeForThePeriod", "ProfitOrLossAttributableToOwnersOfParent", 183 | "ProfitOrLossAttributableToNonControllingInterests", 184 | "ComprehensiveIncomeForThePeriodAttributableToOwnersOfParent", 185 | "ComprehensiveIncomeForThePeriodAttributableToOwnersOfParentNonControllingInterests", 186 | "PaidUpValueOfEquityShareCapital", "FaceValueOfEquityShareCapital", 187 | "BasicEarningsLossPerShareFromContinuingOperations", 188 | "DilutedEarningsLossPerShareFromContinuingOperations", 189 | "BasicEarningsLossPerShareFromDiscontinuedOperations", 190 | "DilutedEarningsLossPerShareFromDiscontinuedOperations", 191 | "BasicEarningsLossPerShareFromContinuingAndDiscontinuedOperations", 192 | "DilutedEarningsLossPerShareFromContinuingAndDiscontinuedOperations", 193 | "DescriptionOfOtherExpenses", "OtherExpenses", 194 | "DescriptionOfItemThatWillNotBeReclassifiedToProfitAndLoss", 195 | "AmountOfItemThatWillNotBeReclassifiedToProfitAndLoss", 196 | "IncomeTaxRelatingToItemsThatWillNotBeReclassifiedToProfitOrLoss", 197 | "DescriptionOfItemThatWillBeReclassifiedToProfitAndLoss", 198 | "AmountOfItemThatWillBeReclassifiedToProfitAndLoss", 199 | "IncomeTaxRelatingToItemsThatWillBeReclassifiedToProfitOrLoss" 200 | ] 201 | return master_data_df, headers, ns, keys_to_extract 202 | 203 | 204 | def get_top_gainers_or_losers(to_get: str): 205 | origin_url = "https://www.nseindia.com/market-data/top-gainers-losers" 206 | url = f"https://www.nseindia.com/api/live-analysis-variations?index={to_get}" 207 | try: 208 | data_json = nse_urlfetch(url, origin_url=origin_url).json() 209 | except Exception as e: 210 | raise NSEdataNotFound(f" Resource not available MSG: {e}") 211 | return data_json 212 | -------------------------------------------------------------------------------- /nselib/derivatives/derivative_data.py: -------------------------------------------------------------------------------- 1 | import datetime as dt 2 | import zipfile 3 | from nselib.derivatives.get_func import * 4 | 5 | 6 | def future_price_volume_data(symbol: str, instrument: str, from_date: str = None, to_date: str = None, 7 | period: str = None): 8 | """ 9 | get contract wise future price volume data set. 10 | :param instrument: FUTIDX/FUTSTK 11 | :param symbol: symbol eg: 'SBIN' / 'BANKNIFTY' 12 | :param from_date: '17-03-2022' ('dd-mm-YYYY') 13 | :param to_date: '17-06-2023' ('dd-mm-YYYY') 14 | :param period: use one {'1D': last day data, 15 | '1W': for last 7 days data, 16 | '1M': from last month same date, 17 | '3M': last 3 month data 18 | '6M': last 6 month data} 19 | :return: pandas.DataFrame 20 | :raise ValueError if the parameter input is not proper 21 | """ 22 | validate_date_param(from_date, to_date, period) 23 | symbol, instrument = cleaning_nse_symbol(symbol=symbol), instrument.upper() 24 | if instrument not in ['FUTIDX', 'FUTSTK']: 25 | raise ValueError(f'{instrument} is not a future instrument') 26 | 27 | from_date, to_date = derive_from_and_to_date(from_date=from_date, to_date=to_date, period=period) 28 | nse_df = pd.DataFrame(columns=future_price_volume_data_column) 29 | from_date = datetime.strptime(from_date, dd_mm_yyyy) 30 | to_date = datetime.strptime(to_date, dd_mm_yyyy) 31 | load_days = (to_date - from_date).days 32 | while load_days > 0: 33 | if load_days > 90: 34 | end_date = (from_date + dt.timedelta(90)).strftime(dd_mm_yyyy) 35 | start_date = from_date.strftime(dd_mm_yyyy) 36 | else: 37 | end_date = to_date.strftime(dd_mm_yyyy) 38 | start_date = from_date.strftime(dd_mm_yyyy) 39 | data_df = get_future_price_volume_data(symbol=symbol, instrument=instrument, 40 | from_date=start_date, to_date=end_date) 41 | from_date = from_date + dt.timedelta(91) 42 | load_days = (to_date - from_date).days 43 | if nse_df.empty: 44 | nse_df = data_df 45 | else: 46 | nse_df = pd.concat([nse_df, data_df], ignore_index=True) 47 | return nse_df 48 | 49 | 50 | def option_price_volume_data(symbol: str, instrument: str, option_type: str = None, from_date: str = None, 51 | to_date: str = None, period: str = None): 52 | """ 53 | get contract wise option price volume data set. more than 90 days will take more time to collect data. 54 | :param option_type: PE/CE 55 | :param instrument: OPTIDX/OPTSTK 56 | :param symbol: symbol eg: 'SBIN' / 'BANKNIFTY' 57 | :param from_date: '17-03-2022' ('dd-mm-YYYY') 58 | :param to_date: '17-06-2023' ('dd-mm-YYYY') 59 | :param period: use one {'1D': last day data, 60 | '1W': for last 7 days data, 61 | '1M': from last month same date, 62 | '3M': last 3 month data 63 | '6M': last 6 month data} 64 | :return: pandas.DataFrame 65 | :raise ValueError if the parameter input is not proper 66 | """ 67 | validate_date_param(from_date, to_date, period) 68 | symbol, instrument = cleaning_nse_symbol(symbol=symbol), instrument.upper() 69 | if instrument not in ['OPTIDX', 'OPTSTK']: 70 | raise ValueError(f'{instrument} is not a future instrument') 71 | 72 | if option_type and option_type not in ['PE', 'CE']: 73 | raise ValueError(f'{option_type} is not a valid option type') 74 | 75 | option_type = [option_type] if option_type else ['PE', 'CE'] 76 | from_date, to_date = derive_from_and_to_date(from_date=from_date, to_date=to_date, period=period) 77 | nse_df = pd.DataFrame(columns=future_price_volume_data_column) 78 | from_date = datetime.strptime(from_date, dd_mm_yyyy) 79 | to_date = datetime.strptime(to_date, dd_mm_yyyy) 80 | load_days = (to_date - from_date).days 81 | while load_days > 0: 82 | if load_days > 90: 83 | end_date = (from_date + dt.timedelta(90)).strftime(dd_mm_yyyy) 84 | start_date = from_date.strftime(dd_mm_yyyy) 85 | else: 86 | end_date = to_date.strftime(dd_mm_yyyy) 87 | start_date = from_date.strftime(dd_mm_yyyy) 88 | for opt_typ in option_type: 89 | data_df = get_option_price_volume_data(symbol=symbol, instrument=instrument, option_type=opt_typ, 90 | from_date=start_date, to_date=end_date) 91 | if nse_df.empty: 92 | nse_df = data_df 93 | else: 94 | nse_df = pd.concat([nse_df, data_df], ignore_index=True) 95 | from_date = from_date + dt.timedelta(91) 96 | load_days = (to_date - from_date).days 97 | 98 | return nse_df 99 | 100 | 101 | def fno_bhav_copy(trade_date: str): 102 | """ 103 | new CM-UDiFF Common NSE future option bhav copy from 2018 on wards 104 | :param trade_date: eg:'20-06-2023' 105 | :return: pandas Data frame 106 | """ 107 | trade_date = datetime.strptime(trade_date, dd_mm_yyyy) 108 | url = 'https://nsearchives.nseindia.com/content/fo/BhavCopy_NSE_FO_0_0_0_' 109 | payload = f"{str(trade_date.strftime('%Y%m%d'))}_F_0000.csv.zip" 110 | request_bhav = nse_urlfetch(url + payload) 111 | bhav_df = pd.DataFrame() 112 | if request_bhav.status_code == 200: 113 | zip_bhav = zipfile.ZipFile(BytesIO(request_bhav.content), 'r') 114 | for file_name in zip_bhav.filelist: 115 | if file_name: 116 | bhav_df = pd.read_csv(zip_bhav.open(file_name)) 117 | elif request_bhav.status_code == 403: 118 | url2 = "https://www.nseindia.com/api/reports?archives=" \ 119 | "%5B%7B%22name%22%3A%22F%26O%20-%20Bhavcopy(csv)%22%2C%22type%22%3A%22archives%22%2C%22category%22" \ 120 | f"%3A%22derivatives%22%2C%22section%22%3A%22equity%22%7D%5D&date={str(trade_date.strftime('%d-%b-%Y'))}" \ 121 | f"&type=equity&mode=single" 122 | request_bhav = nse_urlfetch(url2) 123 | if request_bhav.status_code == 200: 124 | zip_bhav = zipfile.ZipFile(BytesIO(request_bhav.content), 'r') 125 | for file_name in zip_bhav.filelist: 126 | if file_name: 127 | bhav_df = pd.read_csv(zip_bhav.open(file_name)) 128 | elif request_bhav.status_code == 403: 129 | raise FileNotFoundError(f' Data not found, change the date...') 130 | # bhav_df = bhav_df[['INSTRUMENT', 'SYMBOL', 'EXPIRY_DT', 'STRIKE_PR', 'OPTION_TYP', 'OPEN', 'HIGH', 'LOW', 131 | # 'CLOSE', 'SETTLE_PR', 'CONTRACTS', 'VAL_INLAKH', 'OPEN_INT', 'CHG_IN_OI', 'TIMESTAMP']] 132 | return bhav_df 133 | 134 | 135 | def participant_wise_open_interest(trade_date: str): 136 | """ 137 | get FII, DII, Pro, Client wise participant OI data as per traded date 138 | :param trade_date: eg:'20-06-2023' 139 | :return: pandas Data frame 140 | """ 141 | trade_date = datetime.strptime(trade_date, dd_mm_yyyy) 142 | url = f"https://nsearchives.nseindia.com/content/nsccl/fao_participant_oi_{str(trade_date.strftime('%d%m%Y'))}.csv" 143 | # payload = f"{str(for_date.strftime('%d%m%Y'))}.csv" 144 | file_chk = nse_urlfetch(url) 145 | if file_chk.status_code == 404: 146 | url = f"https://archives.nseindia.com/content/nsccl/fao_participant_oi_{str(trade_date.strftime('%d%m%Y'))}.csv" 147 | file_chk = nse_urlfetch(url) 148 | if file_chk.status_code != 200: 149 | raise FileNotFoundError(f" No data available for : {trade_date}") 150 | try: 151 | # data_df = pd.read_csv(url, engine='python', sep=',', quotechar='"', on_bad_lines='skip', skiprows=1) 152 | data_df = pd.read_csv(BytesIO(file_chk.content), on_bad_lines='skip', skiprows=1) 153 | except: 154 | data_df = pd.read_csv(BytesIO(file_chk.content), on_bad_lines='skip', skiprows=1) 155 | data_df.drop(data_df.tail(1).index, inplace=True) 156 | data_df.columns = [name.replace('\t', '') for name in data_df.columns] 157 | return data_df 158 | 159 | 160 | def participant_wise_trading_volume(trade_date: str): 161 | """ 162 | get FII, DII, Pro, Client wise participant volume data as per traded date 163 | :param trade_date: eg:'20-06-2023' 164 | :return: pandas Data frame 165 | """ 166 | trade_date = datetime.strptime(trade_date, dd_mm_yyyy) 167 | url = f"https://nsearchives.nseindia.com/content/nsccl/fao_participant_vol_{str(trade_date.strftime('%d%m%Y'))}.csv" 168 | # payload = f"{str(for_date.strftime('%d%m%Y'))}.csv" 169 | file_chk = nse_urlfetch(url) 170 | if file_chk.status_code != 200: 171 | raise FileNotFoundError(f" No data available for : {trade_date}") 172 | try: 173 | data_df = pd.read_csv(BytesIO(file_chk.content), on_bad_lines='skip', skiprows=1) 174 | except Exception: 175 | data_df = pd.read_csv(BytesIO(file_chk.content), engine='c', sep=',', quotechar='"', 176 | on_bad_lines='skip', skiprows=1) 177 | data_df.drop(data_df.tail(1).index, inplace=True) 178 | data_df.columns = [name.replace('\t', '') for name in data_df.columns] 179 | return data_df 180 | 181 | 182 | def fii_derivatives_statistics(trade_date: str): 183 | """ 184 | get FII derivatives statistics as per the traded date provided 185 | :param trade_date: eg:'20-06-2023' 186 | :return: pandas dataframe 187 | """ 188 | t_date = pd.to_datetime(trade_date, format='%d-%m-%Y') 189 | trade_date = t_date.strftime('%d-%b-%Y') 190 | url = f"https://nsearchives.nseindia.com/content/fo/fii_stats_{trade_date}.xls" 191 | file_chk = nse_urlfetch(url) 192 | if file_chk.status_code != 200: 193 | raise FileNotFoundError(f" No data available for : {trade_date}") 194 | try: 195 | bhav_df = pd.read_excel(BytesIO(file_chk.content), skiprows=3, skipfooter=10).dropna() 196 | bhav_df.columns = ['fii_derivatives', 'buy_contracts', 'buy_value_in_Cr', 'sell_contracts', 'sell_value_in_Cr', 197 | 'open_contracts', 'open_contracts_value_in_Cr'] 198 | except Exception as e: 199 | raise FileNotFoundError(f' FII derivatives statistics not found for : {trade_date} :: NSE error : {e}') 200 | return bhav_df 201 | 202 | 203 | def expiry_dates_future(): 204 | """ 205 | get the future and option expiry dates as per stock or index given 206 | :return: list of dates 207 | """ 208 | origin_url = "https://www.nseindia.com/option-chain" 209 | payload = nse_urlfetch(f'https://www.nseindia.com/api/option-chain-contract-info?symbol=TCS', 210 | origin_url=origin_url).json() 211 | return payload['expiryDates'] 212 | 213 | 214 | def expiry_dates_option_index(): 215 | """ 216 | get the future and option expiry dates as per stock or index given 217 | :return: dictionary 218 | """ 219 | # data_df = pd.DataFrame(columns=['index', 'expiry_date']) 220 | data_dict = {} 221 | for ind in indices_list: 222 | origin_url = "https://www.nseindia.com/option-chain" 223 | payload = nse_urlfetch(f'https://www.nseindia.com/api/option-chain-contract-info?symbol={ind}', 224 | origin_url=origin_url).json() 225 | data_dict.update({ind: payload['expiryDates']}) 226 | return data_dict 227 | 228 | 229 | def nse_live_option_chain(symbol: str, expiry_date: str = None, oi_mode: str = "full"): 230 | """ 231 | get live nse option chain. 232 | :param symbol: eg:SBIN/BANKNIFTY 233 | :param expiry_date: '20-06-2023' 234 | :param oi_mode: eg: full/compact 235 | :return: pands dataframe 236 | """ 237 | 238 | if expiry_date: 239 | exp_date = pd.to_datetime(expiry_date, format='%d-%m-%Y') 240 | expiry_date = pd.to_datetime(exp_date, format='%d-%m-%Y').strftime('%d-%b-%Y') 241 | payload = get_nse_option_chain(symbol, expiry_date).json() 242 | if oi_mode == 'compact': 243 | col_names = ['Fetch_Time', 'Symbol', 'Expiry_Date', 'CALLS_OI', 'CALLS_Chng_in_OI', 'CALLS_Volume', 'CALLS_IV', 244 | 'CALLS_LTP', 'CALLS_Net_Chng', 'Strike_Price', 'PUTS_OI', 'PUTS_Chng_in_OI', 'PUTS_Volume', 245 | 'PUTS_IV', 'PUTS_LTP', 'PUTS_Net_Chng'] 246 | else: 247 | col_names = ['Fetch_Time', 'Symbol', 'Expiry_Date', 'CALLS_OI', 'CALLS_Chng_in_OI', 'CALLS_Volume', 'CALLS_IV', 248 | 'CALLS_LTP', 'CALLS_Net_Chng', 'CALLS_Bid_Qty', 'CALLS_Bid_Price', 'CALLS_Ask_Price', 249 | 'CALLS_Ask_Qty', 'Strike_Price', 'PUTS_Bid_Qty', 'PUTS_Bid_Price', 'PUTS_Ask_Price', 'PUTS_Ask_Qty', 250 | 'PUTS_Net_Chng', 'PUTS_LTP', 'PUTS_IV', 'PUTS_Volume', 'PUTS_Chng_in_OI', 'PUTS_OI'] 251 | 252 | oi_data = pd.DataFrame(columns=col_names) 253 | 254 | oi_row = {'Fetch_Time': None, 'Symbol': None, 'Expiry_Date': None, 'CALLS_OI': 0, 'CALLS_Chng_in_OI': 0, 'CALLS_Volume': 0, 255 | 'CALLS_IV': 0, 'CALLS_LTP': 0, 'CALLS_Net_Chng': 0, 'CALLS_Bid_Qty': 0, 'CALLS_Bid_Price': 0, 256 | 'CALLS_Ask_Price': 0, 'CALLS_Ask_Qty': 0, 'Strike_Price': 0, 'PUTS_OI': 0, 'PUTS_Chng_in_OI': 0, 257 | 'PUTS_Volume': 0, 'PUTS_IV': 0, 'PUTS_LTP': 0, 'PUTS_Net_Chng': 0, 'PUTS_Bid_Qty': 0, 258 | 'PUTS_Bid_Price': 0, 'PUTS_Ask_Price': 0, 'PUTS_Ask_Qty': 0} 259 | 260 | # print(expiry_date) 261 | for m in range(len(payload['records']['data'])): 262 | if not expiry_date or (payload['records']['data'][m]['expiryDates'] == expiry_date): 263 | try: 264 | oi_row['Expiry_Date'] = payload['records']['data'][m]['expiryDates'] 265 | oi_row['CALLS_OI'] = payload['records']['data'][m]['CE']['openInterest'] 266 | oi_row['CALLS_Chng_in_OI'] = payload['records']['data'][m]['CE']['changeinOpenInterest'] 267 | oi_row['CALLS_Volume'] = payload['records']['data'][m]['CE']['totalTradedVolume'] 268 | oi_row['CALLS_IV'] = payload['records']['data'][m]['CE']['impliedVolatility'] 269 | oi_row['CALLS_LTP'] = payload['records']['data'][m]['CE']['lastPrice'] 270 | oi_row['CALLS_Net_Chng'] = payload['records']['data'][m]['CE']['change'] 271 | if oi_mode == 'full': 272 | oi_row['CALLS_Bid_Qty'] = payload['records']['data'][m]['CE']['buyQuantity1'] 273 | oi_row['CALLS_Bid_Price'] = payload['records']['data'][m]['CE']['buyPrice1'] 274 | oi_row['CALLS_Ask_Price'] = payload['records']['data'][m]['CE']['sellPrice1'] 275 | oi_row['CALLS_Ask_Qty'] = payload['records']['data'][m]['CE']['sellQuantity1'] 276 | except KeyError: 277 | oi_row['CALLS_OI'], oi_row['CALLS_Chng_in_OI'], oi_row['CALLS_Volume'], oi_row['CALLS_IV'], oi_row[ 278 | 'CALLS_LTP'], oi_row['CALLS_Net_Chng'] = 0, 0, 0, 0, 0, 0 279 | if oi_mode == 'full': 280 | oi_row['CALLS_Bid_Qty'], oi_row['CALLS_Bid_Price'], oi_row['CALLS_Ask_Price'], oi_row[ 281 | 'CALLS_Ask_Qty'] = 0, 0, 0, 0 282 | pass 283 | 284 | oi_row['Strike_Price'] = payload['records']['data'][m]['strikePrice'] 285 | 286 | try: 287 | oi_row['PUTS_OI'] = payload['records']['data'][m]['PE']['openInterest'] 288 | oi_row['PUTS_Chng_in_OI'] = payload['records']['data'][m]['PE']['changeinOpenInterest'] 289 | oi_row['PUTS_Volume'] = payload['records']['data'][m]['PE']['totalTradedVolume'] 290 | oi_row['PUTS_IV'] = payload['records']['data'][m]['PE']['impliedVolatility'] 291 | oi_row['PUTS_LTP'] = payload['records']['data'][m]['PE']['lastPrice'] 292 | oi_row['PUTS_Net_Chng'] = payload['records']['data'][m]['PE']['change'] 293 | if oi_mode == 'full': 294 | oi_row['PUTS_Bid_Qty'] = payload['records']['data'][m]['PE']['buyQuantity1'] 295 | oi_row['PUTS_Bid_Price'] = payload['records']['data'][m]['PE']['buyPrice1'] 296 | oi_row['PUTS_Ask_Price'] = payload['records']['data'][m]['PE']['sellPrice1'] 297 | oi_row['PUTS_Ask_Qty'] = payload['records']['data'][m]['PE']['sellQuantity1'] 298 | except KeyError: 299 | oi_row['PUTS_OI'], oi_row['PUTS_Chng_in_OI'], oi_row['PUTS_Volume'], oi_row['PUTS_IV'], oi_row[ 300 | 'PUTS_LTP'], oi_row['PUTS_Net_Chng'] = 0, 0, 0, 0, 0, 0 301 | if oi_mode == 'full': 302 | oi_row['PUTS_Bid_Qty'], oi_row['PUTS_Bid_Price'], oi_row['PUTS_Ask_Price'], oi_row[ 303 | 'PUTS_Ask_Qty'] = 0, 0, 0, 0 304 | 305 | # if oi_mode == 'full': 306 | # oi_row['CALLS_Chart'], oi_row['PUTS_Chart'] = 0, 0 307 | if oi_data.empty: 308 | oi_data = pd.DataFrame([oi_row]).copy() 309 | else: 310 | oi_data = pd.concat([oi_data, pd.DataFrame([oi_row])], ignore_index=True) 311 | oi_data['Symbol'] = symbol 312 | oi_data['Fetch_Time'] = payload['records']['timestamp'] 313 | return oi_data 314 | 315 | 316 | def fno_security_in_ban_period(trade_date: str): 317 | """ 318 | To get the list of securities which are baned from fno segment to trade 319 | :param trade_date: eg:'20-06-2023' 320 | :return: pandas Data frame 321 | """ 322 | trade_date = datetime.strptime(trade_date, dd_mm_yyyy) 323 | url = 'https://nsearchives.nseindia.com/archives/fo/sec_ban/fo_secban_' 324 | payload = f"{str(trade_date.strftime('%d%m%Y'))}.csv" 325 | request = nse_urlfetch(url + payload) 326 | securities = [] 327 | if request.status_code == 200: 328 | lines = request.content.decode("utf-8").strip().split("\n") 329 | securities = [line.split(",")[1] for line in lines[1:]] 330 | elif request.status_code == 403: 331 | url2 = "https://www.nseindia.com/api/reports?archives=" \ 332 | "%5B%7B%22name%22%3A%22F%26O%20-%20Security%20in%20ban%20period%22%2C%22type%22%3A%22archives%22%2C%22category%22" \ 333 | f"%3A%22derivatives%22%2C%22section%22%3A%22equity%22%7D%5D&date={str(trade_date.strftime('%d-%b-%Y'))}" \ 334 | f"&type=equity&mode=single" 335 | request = nse_urlfetch(url2) 336 | if request.status_code == 200: 337 | lines = request.content.decode("utf-8").strip().split("\n") 338 | securities = [line.split(",")[1] for line in lines[1:]] 339 | elif request.status_code == 403: 340 | raise FileNotFoundError(f' Data not found, change the date...') 341 | return securities 342 | 343 | 344 | def live_most_active_underlying(): 345 | """ 346 | to get most active underlyings in live market, after market hour it will get as per last traded value 347 | link : https://www.nseindia.com/market-data/most-active-underlying 348 | :return: pandas dataframe 349 | """ 350 | origin_url = "https://www.nseindia.com/market-data/most-active-underlying" 351 | url = f"https://www.nseindia.com/api/live-analysis-most-active-underlying" 352 | try: 353 | data_json = nse_urlfetch(url, origin_url=origin_url).json() 354 | data_df = pd.DataFrame(data_json['data']) 355 | except Exception as e: 356 | raise NSEdataNotFound(f" Resource not available MSG: {e}") 357 | return data_df 358 | 359 | 360 | # if __name__ == '__main__': 361 | # df = future_price_volume_data("BANKNIFTY", "FUTIDX", from_date='01-11-2025', to_date='08-12-2025', period='6M') 362 | # df = option_price_volume_data('NIFTY', 'OPTIDX', period='1D') 363 | # df = get_nse_option_chain(symbol='TCS', expiry_date='30-Dec-2025').json() 364 | # df = fii_derivatives_statistics(trade_date='16-09-2024') 365 | # df = participant_wise_trading_volume(trade_date='16-09-2024') 366 | # df = fno_security_in_ban_period(trade_date='26-03-2025') 367 | # df = expiry_dates_option_index() 368 | # df = expiry_dates_future() 369 | # df = fno_bhav_copy('17-02-2025') 370 | # df = option_price_volume_data('NIFTY', 'OPTIDX', option_type='PE', period='1D') 371 | # df = nse_live_option_chain(symbol="TCS", expiry_date='30-12-2025', oi_mode="full") 372 | # df = live_most_active_underlying() 373 | # print(df) 374 | # print(df.columns) 375 | # print(df[df['EXPIRY_DT']=='27-Jul-2023']) 376 | 377 | -------------------------------------------------------------------------------- /nselib/indices/config.py: -------------------------------------------------------------------------------- 1 | class NiftySectoralIndices: 2 | indices_list = ["Nifty Auto", "Nifty Bank", "Nifty Chemicals", "Nifty Financial Services", "Nifty FMCG", 3 | "Nifty Healthcare", "Nifty IT", "Nifty Media", "Nifty Metal", "Nifty Pharma", "Nifty Private Bank", 4 | "Nifty PSU Bank", "Nifty Realty", "Nifty Consumer Durables", "Nifty Oil and Gas", 5 | "Nifty500 Healthcare", "Nifty MidSmall Financial Services", "Nifty MidSmall Healthcare", 6 | "Nifty MidSmall IT & Telecom"] 7 | index_constituent_list_urls = { 8 | "Nifty Auto": "https://www.niftyindices.com/IndexConstituent/ind_niftyautolist.csv", 9 | "Nifty Bank": "https://www.niftyindices.com/IndexConstituent/ind_niftybanklist.csv", 10 | "Nifty Chemicals": "https://niftyindices.com/IndexConstituent/ind_niftyChemicals_list.csv", 11 | "Nifty Financial Services": "https://www.niftyindices.com/IndexConstituent/ind_niftyfinancelist.csv", 12 | "Nifty FMCG": "https://www.niftyindices.com/IndexConstituent/ind_niftyfmcglist.csv", 13 | "Nifty Healthcare": "https://www.niftyindices.com/IndexConstituent/ind_niftyhealthcarelist.csv", 14 | "Nifty IT": "https://www.niftyindices.com/IndexConstituent/ind_niftyitlist.csv", 15 | "Nifty Media": "https://www.niftyindices.com/IndexConstituent/ind_niftymedialist.csv", 16 | "Nifty Metal": "https://www.niftyindices.com/IndexConstituent/ind_niftymetallist.csv", 17 | "Nifty Pharma": "https://www.niftyindices.com/IndexConstituent/ind_niftypharmalist.csv", 18 | "Nifty Private Bank": "https://www.niftyindices.com/IndexConstituent/ind_nifty_privatebanklist.csv", 19 | "Nifty PSU Bank": "https://www.niftyindices.com/IndexConstituent/ind_niftypsubanklist.csv", 20 | "Nifty Realty": "https://www.niftyindices.com/IndexConstituent/ind_niftyrealtylist.csv", 21 | "Nifty Consumer Durables": "https://www.niftyindices.com/IndexConstituent/ind_niftyconsumerdurableslist.csv", 22 | "Nifty Oil and Gas": "https://www.niftyindices.com/IndexConstituent/ind_niftyoilgaslist.csv", 23 | "Nifty500 Healthcare": "https://niftyindices.com/IndexConstituent/ind_nifty500Healthcare_list.csv", 24 | "Nifty MidSmall Financial Services": "https://www.niftyindices.com/IndexConstituent/ind_niftymidsmallfinancailservice_list.csv", 25 | "Nifty MidSmall Healthcare": "https://www.niftyindices.com/IndexConstituent/ind_niftymidsmallhealthcare_list.csv", 26 | "Nifty MidSmall IT & Telecom": "https://www.niftyindices.com/IndexConstituent/ind_niftymidsmallitAndtelecom_list.csv" 27 | } 28 | index_factsheet_urls = { 29 | "Nifty Auto": "https://www.niftyindices.com/Factsheet/ind_nifty_auto.pdf", 30 | "Nifty Bank": "https://www.niftyindices.com/Factsheet/ind_nifty_bank.pdf", 31 | "Nifty Chemicals": "https://niftyindices.com/Factsheet/Factsheet_Nifty_Chemicals.pdf", 32 | "Nifty Financial Services": "https://www.niftyindices.com/Factsheet/ind_Nifty_Financial_Services.pdf", 33 | "Nifty FMCG": "https://www.niftyindices.com/Factsheet/ind_nifty_FMCG.pdf", 34 | "Nifty Healthcare": "https://www.niftyindices.com/Factsheet/Factsheet_Nifty_Healthcare_Index.pdf", 35 | "Nifty IT": "https://www.niftyindices.com/Factsheet/ind_nifty_it.pdf", 36 | "Nifty Media": "https://www.niftyindices.com/Factsheet/ind_nifty_media.pdf", 37 | "Nifty Metal": "https://www.niftyindices.com/Factsheet/ind_nifty_metal.pdf", 38 | "Nifty Pharma": "https://www.niftyindices.com/Factsheet/ind_nifty_pharma.pdf", 39 | "Nifty Private Bank": "https://www.niftyindices.com/Factsheet/ind_nifty_private_bank.pdf", 40 | "Nifty PSU Bank": "https://www.niftyindices.com/Factsheet/ind_nifty_psu_bank.pdf", 41 | "Nifty Realty": "https://www.niftyindices.com/Factsheet/ind_nifty_realty.pdf", 42 | "Nifty Consumer Durables": "https://www.niftyindices.com/Factsheet/Factsheet_nifty_consumer_durables.pdf", 43 | "Nifty Oil and Gas": "https://www.niftyindices.com/Factsheet/Factsheet_nifty_oil_and_gas.pdf", 44 | "Nifty500 Healthcare": "https://niftyindices.com/Factsheet/Factsheet_Nifty500Healthcare.pdf", 45 | "Nifty MidSmall Financial Services": "https://www.niftyindices.com/Factsheet/Factsheet_NiftyMidSmallFinancialSevices.pdf", 46 | "Nifty MidSmall Healthcare": "https://www.niftyindices.com/Factsheet/Factsheet_NiftyMidSmallHealthCare.pdf", 47 | "Nifty MidSmall IT & Telecom": "https://www.niftyindices.com/Factsheet/Factsheet_NiftyMidSmallITAndTelecom.pdf" 48 | } 49 | 50 | 51 | class NiftyBroadMarketIndices: 52 | indices_list = ["Nifty 50", "Nifty Next 50", "Nifty 100", "Nifty 200", "Nifty Total Market", "Nifty 500", 53 | "Nifty Midcap150", "Nifty Midcap 50", "Nifty Midcap Select", "Nifty Midcap 100", 54 | "Nifty Smallcap 250", "Nifty Smallcap 50", "Nifty Smallcap 100", "Nifty Microcap 250", 55 | "Nifty LargeMidcap 250", "Nifty MidSmallcap 400", "Nifty India FPI 150", "India Vix"] 56 | index_constituent_list_urls = { 57 | "Nifty 50": "https://nsearchives.nseindia.com/content/indices/ind_nifty50list.csv", 58 | "Nifty Next 50": "https://nsearchives.nseindia.com/content/indices/ind_niftynext50list.csv", 59 | "Nifty 100": "https://nsearchives.nseindia.com/content/indices/ind_nifty100list.csv", 60 | "Nifty 200": "https://nsearchives.nseindia.com/content/indices/ind_nifty200list.csv", 61 | "Nifty Total Market": "https://nsearchives.nseindia.com/content/indices/ind_niftytotalmarket_list.csv", 62 | "Nifty 500": "https://nsearchives.nseindia.com/content/indices/ind_nifty500list.csv", 63 | "Nifty Midcap150": "https://nsearchives.nseindia.com/content/indices/ind_niftymidcap150list.csv", 64 | "Nifty Midcap 50": "https://nsearchives.nseindia.com/content/indices/ind_niftymidcap50list.csv", 65 | "Nifty Midcap Select": "https://nsearchives.nseindia.com/content/indices/ind_niftymidcapselect_list.csv", 66 | "Nifty Midcap 100": "https://nsearchives.nseindia.com/content/indices/ind_niftymidcap100list.csv", 67 | "Nifty Smallcap 250": "https://nsearchives.nseindia.com/content/indices/ind_niftysmallcap250list.csv", 68 | "Nifty Smallcap 50": "https://nsearchives.nseindia.com/content/indices/ind_niftysmallcap50list.csv", 69 | "Nifty Smallcap 100": "https://nsearchives.nseindia.com/content/indices/ind_niftysmallcap100list.csv", 70 | "Nifty Microcap 250": "https://nsearchives.nseindia.com/content/indices/ind_niftymicrocap250_list.csv", 71 | "Nifty LargeMidcap 250": "https://nsearchives.nseindia.com/content/indices/ind_niftylargemidcap250list.csv", 72 | "Nifty MidSmallcap 400": "https://nsearchives.nseindia.com/content/indices/ind_niftymidsmallcap400list.csv", 73 | "Nifty India FPI 150": "https://niftyindices.com/IndexConstituent/ind_niftyIndiaFPI150_list.csv" 74 | } 75 | index_factsheet_urls = { 76 | "Nifty 50": "https://nsearchives.nseindia.com/content/indices/ind_nifty50.pdf", 77 | "Nifty Next 50": "https://nsearchives.nseindia.com/content/indices/ind_next50.pdf", 78 | "Nifty 100": "https://nsearchives.nseindia.com/content/indices/ind_nifty_100.pdf", 79 | "Nifty 200": "https://nsearchives.nseindia.com/content/indices/ind_nifty_200.pdf", 80 | "Nifty Total Market": "https://nsearchives.nseindia.com/content/indices/Factsheet_NiftyTotalMarket.pdf", 81 | "Nifty 500": "https://nsearchives.nseindia.com/content/indices/ind_nifty_500.pdf", 82 | "Nifty Midcap150": "https://nsearchives.nseindia.com/content/indices/ind_Nifty_Midcap_150.pdf", 83 | "Nifty Midcap 50": "https://nsearchives.nseindia.com/content/indices/ind_nifty_midcap50.pdf", 84 | "Nifty Midcap Select": "https://nsearchives.nseindia.com/content/indices/Factsheet_NiftyMidcapSelect.pdf", 85 | "Nifty Midcap 100": "https://nsearchives.nseindia.com/content/indices/ind_niftymidcap100.pdf", 86 | "Nifty Smallcap 250": "https://nsearchives.nseindia.com/content/indices/ind_Nifty_Smallcap_250.pdf", 87 | "Nifty Smallcap 50": "https://nsearchives.nseindia.com/content/indices/ind_niftysmallcap_50.pdf", 88 | "Nifty Smallcap 100": "https://nsearchives.nseindia.com/content/indices/ind_niftysmallcap100.pdf", 89 | "Nifty Microcap 250": "https://nsearchives.nseindia.com/content/indices/Factsheet_Nifty_Microcap_250_Index.pdf", 90 | "Nifty LargeMidcap 250": "https://nsearchives.nseindia.com/content/indices/Factsheet_NIFTY_LargeMidcap_250_Index.pdf", 91 | "Nifty MidSmallcap 400": "https://nsearchives.nseindia.com/content/indices/ind_Nifty_MidSmallcap_400.pdf", 92 | "Nifty India FPI 150": "https://niftyindices.com/Factsheet/Factsheet_NiftyIndiaFPI150Index.pdf" 93 | } 94 | 95 | 96 | class NiftyThematicIndices: 97 | indices_list = [ 98 | "Nifty Capital Markets", 99 | "Nifty Commodities", 100 | "Nifty Conglomerate 50", 101 | "Nifty Core Housing", 102 | "Nifty CPSE", 103 | "Nifty EV & New Age Automotive", 104 | "Nifty Energy", 105 | "Nifty Housing", 106 | "Nifty India Consumption", 107 | "Nifty India Defence", 108 | "Nifty India Digital", 109 | "Nifty India Infrastructure & Logistics", 110 | "Nifty India Internet", 111 | "Nifty India Manufacturing", 112 | "Nifty India New Age Consumption", 113 | "Nifty India Railways PSU", 114 | "Nifty India Tourism", 115 | "Nifty Infrastructure", 116 | "Nifty IPO", 117 | "Nifty Midcap Liquid 15", 118 | "Nifty MNC", 119 | "Nifty Mobility", 120 | "Nifty PSE", 121 | "Nifty REITs & InvITs", 122 | "Nifty Rural", 123 | "Nifty Non-Cyclical Consumer", 124 | "Nifty Services Sector", 125 | "Nifty Shariah 25", 126 | "Nifty100 Liquid 15", 127 | "Nifty50 Shariah", 128 | "Nifty500 Shariah", 129 | "Nifty SME EMERGE", 130 | "Nifty Waves", 131 | "Nifty100 ESG", 132 | "Nifty100 Enhanced ESG", 133 | "Nifty100 ESG Sector Leaders", 134 | "Nifty India Corporate Group - Aditya Birla Group", 135 | "Nifty India Corporate Group - Mahindra Group", 136 | "Nifty India Corporate Group - Tata Group", 137 | "Nifty India Select 5 Corporate Groups (MAATR)" 138 | ] 139 | index_constituent_list_urls = { 140 | "Nifty Capital Markets": "https://niftyindices.com/IndexConstituent/ind_niftyCapitalMarkets_list.csv", 141 | "Nifty Commodities": "https://www.niftyindices.com/IndexConstituent/ind_niftycommoditieslist.csv", 142 | "Nifty Conglomerate 50": "https://www.niftyindices.com/IndexConstituent/ind_niftyConglomerate50_list.csv", 143 | "Nifty Core Housing": "https://niftyindices.com/IndexConstituent/ind_niftyCoreHousing_list.csv", 144 | "Nifty CPSE": "https://www.niftyindices.com/IndexConstituent/ind_niftycpselist.csv", 145 | "Nifty EV & New Age Automotive": "https://niftyindices.com/IndexConstituent/ind_niftyEv_NewAgeAutomotive_list.csv", 146 | "Nifty Energy": "https://www.niftyindices.com/IndexConstituent/ind_niftyenergylist.csv", 147 | "Nifty Housing": "https://www.niftyindices.com/IndexConstituent/ind_niftyhousing_list.csv", 148 | "Nifty India Consumption": "https://www.niftyindices.com/IndexConstituent/ind_niftyconsumptionlist.csv", 149 | "Nifty India Defence": "https://www.niftyindices.com/IndexConstituent/ind_niftyindiadefence_list.csv", 150 | "Nifty India Digital": "https://niftyindices.com/IndexConstituent/ind_niftyindiadigital_list.csv", 151 | "Nifty India Infrastructure & Logistics": "https://niftyindices.com/IndexConstituent/ind_niftyIndiaInfrastructure_Logistics_list.csv", 152 | "Nifty India Internet": "https://www.niftyindices.com/IndexConstituent/ind_niftyIndiaInternet_list.csv", 153 | "Nifty India Manufacturing": "https://www.niftyindices.com/IndexConstituent/ind_niftyindiamanufacturing_list.csv", 154 | "Nifty India New Age Consumption": "https://niftyindices.com/IndexConstituent/ind_niftyIndiaNewAgeConsumption_list.csv", 155 | "Nifty India Railways PSU": "https://niftyindices.com/IndexConstituent/ind_niftyIndiaRailwaysPSU_list.csv", 156 | "Nifty India Tourism": "https://niftyindices.com/IndexConstituent/ind_niftyindiatourism_list.csv", 157 | "Nifty Infrastructure": "https://www.niftyindices.com/IndexConstituent/ind_niftyinfralist.csv", 158 | "Nifty IPO": "https://niftyindices.com/IndexConstituent/ind_niftyIPO_list.csv", 159 | "Nifty Midcap Liquid 15": "https://www.niftyindices.com/IndexConstituent/ind_Nifty_Midcap_Liquid15.csv", 160 | "Nifty MNC": "https://www.niftyindices.com/IndexConstituent/ind_niftymnclist.csv", 161 | "Nifty Mobility": "https://www.niftyindices.com/IndexConstituent/ind_niftymobility_list.csv", 162 | "Nifty PSE": "https://www.niftyindices.com/IndexConstituent/ind_niftypselist.csv", 163 | "Nifty REITs & InvITs": "https://www.niftyindices.com/IndexConstituent/ind_niftyREITs_InvITs_list.csv", 164 | "Nifty Rural": "https://niftyindices.com/IndexConstituent/ind_niftyRural_list.csv", 165 | "Nifty Non-Cyclical Consumer": "https://www.niftyindices.com/IndexConstituent/ind_niftynon-cyclicalconsumer_list.csv", 166 | "Nifty Services Sector": "https://www.niftyindices.com/IndexConstituent/ind_niftyservicelist.csv", 167 | "Nifty Shariah 25": "", 168 | "Nifty100 Liquid 15": "https://www.niftyindices.com/IndexConstituent/ind_Nifty100_Liquid15.csv", 169 | "Nifty50 Shariah": "", 170 | "Nifty500 Shariah": "", 171 | "Nifty SME EMERGE": "https://www.niftyindices.com/IndexConstituent/ind_niftysmelist.csv", 172 | "Nifty Waves": "https://niftyindices.com/IndexConstituent/ind_niftyWaves_list.csv", 173 | "Nifty100 ESG": "", 174 | "Nifty100 Enhanced ESG": "", 175 | "Nifty100 ESG Sector Leaders": "", 176 | "Nifty India Corporate Group - Aditya Birla Group": "https://niftyindices.com/IndexConstituent/ind_nifty_adityabirlalist.csv", 177 | "Nifty India Corporate Group - Mahindra Group": "https://niftyindices.com/IndexConstituent/ind_nifty_mahindralist.csv", 178 | "Nifty India Corporate Group - Tata Group": "https://niftyindices.com/IndexConstituent/ind_nifty_tatalist.csv", 179 | "Nifty India Select 5 Corporate Groups (MAATR)": "https://niftyindices.com/IndexConstituent/ind_niftyIndiaSelect5CorporateGroupsMAATR_list.csv" 180 | } 181 | index_factsheet_urls = { 182 | "Nifty Capital Markets": "https://niftyindices.com/Factsheet/Factsheet_NiftyCapitalMarkets.pdf", 183 | "Nifty Commodities": "https://www.niftyindices.com/Factsheet/ind_nifty_commodities.pdf", 184 | "Nifty Conglomerate 50": "https://www.niftyindices.com/Factsheet/Factsheet_NiftyConglomerate50.pdf", 185 | "Nifty Core Housing": "https://niftyindices.com/Factsheet/Nifty_Core_Housing_Factsheet.pdf", 186 | "Nifty CPSE": "https://www.niftyindices.com/Factsheet/ind_Nifty_CPSE.pdf", 187 | "Nifty EV & New Age Automotive": "https://niftyindices.com/Factsheet/Factsheet_NiftyEVNewAgeAutomotive.pdf", 188 | "Nifty Energy": "https://www.niftyindices.com/Factsheet/ind_nifty_energy.pdf", 189 | "Nifty Housing": "https://www.niftyindices.com/Factsheet/Factsheet_NiftyHousing.pdf", 190 | "Nifty India Consumption": "https://www.niftyindices.com/Factsheet/ind_Nifty_India_Consumption.pdf", 191 | "Nifty India Defence": "https://www.niftyindices.com/Factsheet/Factsheet_NiftyIndiaDefence.pdf", 192 | "Nifty India Digital": "https://niftyindices.com/Factsheet/Factsheet_NiftyIndiaDigital.pdf", 193 | "Nifty India Infrastructure & Logistics": "https://niftyindices.com/Factsheet/Factsheet_Nifty_India_Infrastructure_and_Logistics.pdf", 194 | "Nifty India Internet": "https://www.niftyindices.com/Factsheet/Factsheet_Nifty_India_Internet.pdf", 195 | "Nifty India Manufacturing": "https://www.niftyindices.com/Factsheet/Factsheet_Nifty_India_Manufacturing_Index.pdf", 196 | "Nifty India New Age Consumption": "https://niftyindices.com/Factsheet/Factsheet_NiftyIndiaNewAgeConsumption.pdf", 197 | "Nifty India Railways PSU": "https://niftyindices.com/Factsheet/Factsheet_NiftyIndiaRailwaysPSU.pdf", 198 | "Nifty India Tourism": "https://niftyindices.com/Factsheet/Factsheet_NiftyIndiaTourism.pdf", 199 | "Nifty Infrastructure": "https://www.niftyindices.com/Factsheet/ind_nifty_infra.pdf", 200 | "Nifty IPO": "https://niftyindices.com/Factsheet/Factsheet_NiftyIPO.pdf", 201 | "Nifty Midcap Liquid 15": "https://www.niftyindices.com/Factsheet/Nifty_midcap_liquid_15.pdf", 202 | "Nifty MNC": "https://www.niftyindices.com/Factsheet/ind_nifty_mnc.pdf", 203 | "Nifty Mobility": "https://www.niftyindices.com/Factsheet/Factsheet_Nifty_Mobility_Total_Returns_Index.pdf", 204 | "Nifty PSE": "https://www.niftyindices.com/Factsheet/ind_nifty_pse.pdf", 205 | "Nifty REITs & InvITs": "https://www.niftyindices.com/Factsheet/Factsheet_REITs_InvITs.pdf", 206 | "Nifty Rural": "https://niftyindices.com/Factsheet/Factsheet_NiftyRural.pdf", 207 | "Nifty Non-Cyclical Consumer": "https://www.niftyindices.com/Factsheet/Factsheet_NiftyNonCyclicalConsumer.pdf", 208 | "Nifty Services Sector": "https://www.niftyindices.com/Factsheet/ind_nifty_services_sector.pdf", 209 | "Nifty Shariah 25": "https://www.niftyindices.com/Factsheet/Factsheet_nifty_Shariah25.pdf", 210 | "Nifty100 Liquid 15": "https://www.niftyindices.com/Factsheet/Nifty100_Liquid_15.pdf", 211 | "Nifty50 Shariah": "https://www.niftyindices.com/Factsheet/Factsheet_Nifty50_Shariah.pdf", 212 | "Nifty500 Shariah": "https://www.niftyindices.com/Factsheet/Factsheet_Nifty500_Shariah.pdf", 213 | "Nifty SME EMERGE": "https://www.niftyindices.com/Factsheet/Factsheet_NIFTY_SME_EMERGE_Index.pdf", 214 | "Nifty Waves": "https://niftyindices.com/Factsheet/Factsheet_Nifty_Waves.pdf", 215 | "Nifty100 ESG": "https://www.niftyindices.com/Factsheet/Factsheet_NIFTY100_ESG_Index.pdf", 216 | "Nifty100 Enhanced ESG": "https://www.niftyindices.com/Factsheet/Factsheet_NIFTY100_Enhanced_ESG_Index.pdf", 217 | "Nifty100 ESG Sector Leaders": "https://www.niftyindices.com/Factsheet/Factsheet_Nifty100_ESG_Sector_Leaders.pdf", 218 | "Nifty India Corporate Group - Aditya Birla Group": "https://niftyindices.com/Factsheet/ind_NIFTY_ADITYA_BIRLA_GROUP.pdf", 219 | "Nifty India Corporate Group - Mahindra Group": "https://niftyindices.com/Factsheet/ind_NIFTY_MAHINDRA_GROUP.pdf", 220 | "Nifty India Corporate Group - Tata Group": "https://niftyindices.com/Factsheet/Ind_NIFTY_TATA_GROUP.pdf", 221 | "Nifty India Select 5 Corporate Groups (MAATR)": "https://niftyindices.com/Factsheet/Factsheet_NiftyIndiaSelect5CorporateGroupsMAATR.pdf" 222 | } 223 | 224 | 225 | class NiftyStrategyIndices: 226 | indices_list = [ 227 | "Nifty100 Equal Weight", 228 | "Nifty100 Low Volatility 30", 229 | "Nifty200 Momentum 30", 230 | "Nifty200 Alpha 30", 231 | "Nifty100 Alpha 30", 232 | "Nifty Dividend Opportunities 50", 233 | "Nifty Growth Sectors 15", 234 | "Nifty High Beta 50", 235 | "Nifty Low Volatility 50", 236 | "Nifty Top 10 Equal Weight", 237 | "Nifty Top 15 Equal Weight", 238 | "Nifty Top 20 Equal Weight", 239 | "Nifty100 Quality 30", 240 | "Nifty Midcap150 Momentum 50", 241 | "Nifty Midcap150 Quality 50", 242 | "Nifty Alpha 50", 243 | "Nifty50 Equal Weight", 244 | "Nifty50 Value 20", 245 | "Nifty200 Value 30", 246 | "Nifty500 Flexicap Quality 30", 247 | "Nifty500 Value 50", 248 | "Nifty500 Equal Weight", 249 | "Nifty500 Low Volatility 50", 250 | "Nifty500 Momentum 50", 251 | "Nifty500 Quality 50", 252 | "Nifty500 Multifactor MQVLv 50", 253 | "Nifty200 Quality 30", 254 | "Nifty MidSmallcap400 Momentum Quality 100", 255 | "Nifty Smallcap250 Quality 50", 256 | "Nifty Total Market Momentum Quality 50" 257 | ] 258 | index_constituent_list_urls = { 259 | "Nifty100 Equal Weight": "https://www.niftyindices.com/IndexConstituent/ind_nifty100list.csv", 260 | "Nifty100 Low Volatility 30": "https://www.niftyindices.com/IndexConstituent/ind_Nifty100LowVolatility30list.csv", 261 | "Nifty200 Momentum 30": "https://www.niftyindices.com/IndexConstituent/ind_nifty200Momentum30_list.csv", 262 | "Nifty200 Alpha 30": "https://www.niftyindices.com/IndexConstituent/ind_nifty200alpha30_list.csv", 263 | "Nifty100 Alpha 30": "https://www.niftyindices.com/IndexConstituent/ind_nifty100Alpha30list.csv", 264 | "Nifty Dividend Opportunities 50": "https://www.niftyindices.com/IndexConstituent/ind_niftydivopp50list.csv", 265 | "Nifty Growth Sectors 15": "https://www.niftyindices.com/IndexConstituent/ind_NiftyGrowth_Sectors15_Index.csv", 266 | "Nifty High Beta 50": "https://www.niftyindices.com/IndexConstituent/nifty_High_Beta50_Index.csv", 267 | "Nifty Low Volatility 50": "https://www.niftyindices.com/IndexConstituent/nifty_low_Volatility50_Index.csv", 268 | "Nifty Top 10 Equal Weight": "https://niftyindices.com/IndexConstituent/ind_niftytop10EqualWeight_list.csv", 269 | "Nifty Top 15 Equal Weight": "https://niftyindices.com/IndexConstituent/ind_niftytop15EqualWeight_list.csv", 270 | "Nifty Top 20 Equal Weight": "https://niftyindices.com/IndexConstituent/ind_niftyTop20EqualWeight_list.csv", 271 | "Nifty100 Quality 30": "https://www.niftyindices.com/IndexConstituent/ind_nifty100Quality30list.csv", 272 | "Nifty Midcap150 Momentum 50": "https://www.niftyindices.com/IndexConstituent/ind_niftymidcap150momentum50_list.csv", 273 | "Nifty Midcap150 Quality 50": "https://www.niftyindices.com/IndexConstituent/ind_niftymidcap150quality50list.csv", 274 | "Nifty Alpha 50": "https://www.niftyindices.com/IndexConstituent/ind_nifty_Alpha_Index.csv", 275 | "Nifty50 Equal Weight": "https://www.niftyindices.com/IndexConstituent/ind_Nifty50EqualWeight.csv", 276 | "Nifty50 Value 20": "https://www.niftyindices.com/IndexConstituent/ind_Nifty50_Value20.csv", 277 | "Nifty200 Value 30": "https://niftyindices.com/IndexConstituent/ind_nifty200Value30_list.csv", 278 | "Nifty500 Flexicap Quality 30": "https://niftyindices.com/IndexConstituent/ind_nifty500FlexicapQuality30_list.csv", 279 | "Nifty500 Value 50": "https://www.niftyindices.com/IndexConstituent/ind_nifty500Value50_list.csv", 280 | "Nifty500 Equal Weight": "https://niftyindices.com/IndexConstituent/ind_nifty500EqualWeight_list.csv", 281 | "Nifty500 Low Volatility 50": "https://niftyindices.com/IndexConstituent/ind_nifty500LowVolatility50_list.csv", 282 | "Nifty500 Momentum 50": "https://www.niftyindices.com/IndexConstituent/ind_nifty500Momentum50_list.csv", 283 | "Nifty500 Quality 50": "https://niftyindices.com/IndexConstituent/ind_nifty500Quality50_list.csv", 284 | "Nifty500 Multifactor MQVLv 50": "https://niftyindices.com/IndexConstituent/ind_nifty500MultifactorMQVLv50_list.csv", 285 | "Nifty200 Quality 30": "https://www.niftyindices.com/IndexConstituent/ind_nifty200Quality30_list.csv", 286 | "Nifty MidSmallcap400 Momentum Quality 100": "https://www.niftyindices.com/IndexConstituent/ind_niftyMidSmallcap400MomentumQuality100_list.csv", 287 | "Nifty Smallcap250 Quality 50": "https://www.niftyindices.com/IndexConstituent/ind_niftySmallcap250_Quality50_list.csv", 288 | "Nifty Total Market Momentum Quality 50": "https://niftyindices.com/IndexConstituent/ind_niftyTotalMarketMomentumQuality50_list.csv" 289 | } 290 | index_factsheet_urls = { 291 | "Nifty100 Equal Weight": "https://www.niftyindices.com/Factsheet/Factsheet_Nifty_100_EW_Index.pdf", 292 | "Nifty100 Low Volatility 30": "https://www.niftyindices.com/Factsheet/Nifty100_LowVolatility30.pdf", 293 | "Nifty200 Momentum 30": "https://www.niftyindices.com/Factsheet/Factsheet_Nifty200_Momentum30.pdf", 294 | "Nifty200 Alpha 30": "https://www.niftyindices.com/Factsheet/Factsheet_Nifty200Alpha30.pdf", 295 | "Nifty100 Alpha 30": "https://www.niftyindices.com/Factsheet/Factsheet_Nifty100_Alpha30.pdf", 296 | "Nifty Dividend Opportunities 50": "https://www.niftyindices.com/Factsheet/ind_Nifty_Divid_Opp50.pdf", 297 | "Nifty Growth Sectors 15": "https://www.niftyindices.com/Factsheet/Nifty_Growth_Sectors15.pdf", 298 | "Nifty High Beta 50": "https://www.niftyindices.com/Factsheet/Factsheet_nifty_High_Beta50.pdf", 299 | "Nifty Low Volatility 50": "https://www.niftyindices.com/Factsheet/Factsheet_nifty_Low_Volatility50.pdf", 300 | "Nifty Top 10 Equal Weight": "https://niftyindices.com/Factsheet/Factsheet_NiftyTop10EqualWeight.pdf", 301 | "Nifty Top 15 Equal Weight": "https://niftyindices.com/Factsheet/Factsheet_NiftyTop15EqualWeight.pdf", 302 | "Nifty Top 20 Equal Weight": "https://niftyindices.com/Factsheet/Factsheet_NiftyTop20EqualWeight.pdf", 303 | "Nifty100 Quality 30": "https://www.niftyindices.com/Factsheet/Nifty100_Quality30.pdf", 304 | "Nifty Midcap150 Momentum 50": "https://www.niftyindices.com/Factsheet/Factsheet_NiftyMidcap150Momentum50.pdf", 305 | "Nifty Midcap150 Quality 50": "https://www.niftyindices.com/Factsheet/Factsheet_NIFTYMidcap150_Quality50.pdf", 306 | "Nifty Alpha 50": "https://www.niftyindices.com/Factsheet/Factsheet_Nifty_Alpha50.pdf", 307 | "Nifty50 Equal Weight": "https://www.niftyindices.com/Factsheet/Factsheet_NIFTY50_Equal_Weight.pdf", 308 | "Nifty50 Value 20": "https://www.niftyindices.com/Factsheet/Nifty50_Value20.pdf", 309 | "Nifty200 Value 30": "https://niftyindices.com/Factsheet/Factsheet_Nifty200_Value30.pdf", 310 | "Nifty500 Flexicap Quality 30": "https://niftyindices.com/Factsheet/Factsheet_Nifty500_Flexicap_Quality_30.pdf", 311 | "Nifty500 Value 50": "https://www.niftyindices.com/Factsheet/FactsheetNIFTY500Value50.pdf", 312 | "Nifty500 Equal Weight": "https://niftyindices.com/Factsheet/Factsheet_Nifty_500_Equal_Weight.pdf", 313 | "Nifty500 Low Volatility 50": "https://niftyindices.com/Factsheet/Factsheet_Nifty500LowVolatility50.pdf", 314 | "Nifty500 Momentum 50": "https://www.niftyindices.com/Factsheet/FactsheetNifty500Momentum50.pdf", 315 | "Nifty500 Quality 50": "https://niftyindices.com/Factsheet/Factsheet_Nifty500Quality50.pdf", 316 | "Nifty500 Multifactor MQVLv 50": "https://niftyindices.com/Factsheet/Factsheet_Nifty500MultifactorMQVLv50.pdf", 317 | "Nifty200 Quality 30": "https://www.niftyindices.com/Factsheet/Factsheet_NIFTY200_Quality30.pdf", 318 | "Nifty MidSmallcap400 Momentum Quality 100": "https://www.niftyindices.com/Factsheet/Factsheet_NiftyMidSmallcap400MomentumQuality100.pdf", 319 | "Nifty Smallcap250 Quality 50": "https://www.niftyindices.com/Factsheet/Factsheet_NiftySmallcap250Quality50.pdf", 320 | "Nifty Total Market Momentum Quality 50": "https://niftyindices.com/Factsheet/Factsheet_NiftyTotalMarketMomentumQuality50.pdf" 321 | } 322 | -------------------------------------------------------------------------------- /nselib/capital_market/capital_market_data.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import datetime as dt 3 | import zipfile 4 | import xml.etree.ElementTree as ET 5 | from nselib.capital_market.get_func import * 6 | 7 | 8 | # logging.basicConfig(level=logging.DEBUG) 9 | # logging.getLogger("urllib3").setLevel(logging.WARNING) 10 | 11 | 12 | def price_volume_and_deliverable_position_data(symbol: str, from_date: str = None, to_date: str = None, 13 | period: str = None): 14 | """ 15 | get Security wise price volume & Deliverable position data set. use get_nse_symbols() to get all symbols 16 | :param symbol: symbol eg: 'SBIN' 17 | :param from_date: '17-03-2022' ('dd-mm-YYYY') 18 | :param to_date: '17-06-2023' ('dd-mm-YYYY') 19 | :param period: use one {'1D': last day data,'1W': for last 7 days data, 20 | '1M': from last month same date, '6M': last 6 month data, '1Y': from last year same date) 21 | :return: pandas.DataFrame 22 | :raise ValueError if the parameter input is not proper 23 | """ 24 | validate_date_param(from_date, to_date, period) 25 | symbol = cleaning_nse_symbol(symbol=symbol) 26 | from_date, to_date = derive_from_and_to_date(from_date=from_date, to_date=to_date, period=period) 27 | nse_df = pd.DataFrame(columns=price_volume_and_deliverable_position_data_columns) 28 | from_date = datetime.strptime(from_date, dd_mm_yyyy) 29 | to_date = datetime.strptime(to_date, dd_mm_yyyy) 30 | load_days = (to_date - from_date).days 31 | while load_days > 0: 32 | if load_days > 365: 33 | end_date = (from_date + dt.timedelta(364)).strftime(dd_mm_yyyy) 34 | start_date = from_date.strftime(dd_mm_yyyy) 35 | else: 36 | end_date = to_date.strftime(dd_mm_yyyy) 37 | start_date = from_date.strftime(dd_mm_yyyy) 38 | data_df = get_price_volume_and_deliverable_position_data(symbol=symbol, from_date=start_date, to_date=end_date) 39 | from_date = from_date + dt.timedelta(365) 40 | load_days = (to_date - from_date).days 41 | if not data_df.empty: 42 | # Drop all-NaN columns from both frames 43 | data_df = data_df.fillna('-') 44 | nse_df = nse_df.fillna('-') 45 | data_df = data_df.dropna(axis=1, how='all') 46 | nse_df = nse_df.dropna(axis=1, how='all') 47 | if not data_df.empty: 48 | nse_df = pd.concat([nse_df, data_df], ignore_index=True) 49 | 50 | nse_df["TotalTradedQuantity"] = pd.to_numeric(nse_df["TotalTradedQuantity"].astype(str).str.replace(",", ""), errors="coerce") 51 | nse_df["TurnoverInRs"] = pd.to_numeric(nse_df["TurnoverInRs"].astype(str).str.replace(",", ""), errors="coerce") 52 | nse_df["No.ofTrades"] = pd.to_numeric(nse_df["No.ofTrades"].astype(str).str.replace(",", ""), errors="coerce") 53 | nse_df["DeliverableQty"] = pd.to_numeric(nse_df["DeliverableQty"].astype(str).str.replace(",", ""), errors="coerce") 54 | return nse_df 55 | 56 | 57 | def price_volume_data(symbol: str, from_date: str = None, to_date: str = None, period: str = None): 58 | """ 59 | get Security wise price volume data set. 60 | :param symbol: symbol eg: 'SBIN' 61 | :param from_date: '17-03-2022' ('dd-mm-YYYY') 62 | :param to_date: '17-06-2023' ('dd-mm-YYYY') 63 | :param period: use one {'1D': last day data,'1W': for last 7 days data, 64 | '1M': from last month same date, '6M': last 6 month data, '1Y': from last year same date) 65 | :return: pandas.DataFrame 66 | :raise ValueError if the parameter input is not proper 67 | """ 68 | validate_date_param(from_date, to_date, period) 69 | symbol = cleaning_nse_symbol(symbol=symbol) 70 | from_date, to_date = derive_from_and_to_date(from_date=from_date, to_date=to_date, period=period) 71 | nse_df = pd.DataFrame(columns=price_volume_data_columns) 72 | from_date = datetime.strptime(from_date, dd_mm_yyyy) 73 | to_date = datetime.strptime(to_date, dd_mm_yyyy) 74 | load_days = (to_date - from_date).days 75 | while load_days > 0: 76 | if load_days > 365: 77 | end_date = (from_date + dt.timedelta(364)).strftime(dd_mm_yyyy) 78 | start_date = from_date.strftime(dd_mm_yyyy) 79 | else: 80 | end_date = to_date.strftime(dd_mm_yyyy) 81 | start_date = from_date.strftime(dd_mm_yyyy) 82 | data_df = get_price_volume_data(symbol=symbol, from_date=start_date, to_date=end_date) 83 | from_date = from_date + dt.timedelta(365) 84 | load_days = (to_date - from_date).days 85 | if nse_df.empty: 86 | nse_df = data_df 87 | else: 88 | nse_df = pd.concat([nse_df, data_df], ignore_index=True) 89 | return nse_df 90 | 91 | 92 | def deliverable_position_data(symbol: str, from_date: str = None, to_date: str = None, period: str = None): 93 | """ 94 | get Security wise deliverable position data set. 95 | :param symbol: symbol eg: 'SBIN' 96 | :param from_date: '17-03-2022' ('dd-mm-YYYY') 97 | :param to_date: '17-06-2023' ('dd-mm-YYYY') 98 | :param period: use one {'1D': last day data, 99 | '1W': for last 7 days data, 100 | '1M': from last month same date, 101 | '6M': last 6 month data, 102 | '1Y': from last year same date) 103 | :return: pandas.DataFrame 104 | :raise ValueError if the parameter input is not proper 105 | """ 106 | validate_date_param(from_date, to_date, period) 107 | symbol = cleaning_nse_symbol(symbol=symbol) 108 | from_date, to_date = derive_from_and_to_date(from_date=from_date, to_date=to_date, period=period) 109 | nse_df = pd.DataFrame(columns=deliverable_data_columns) 110 | from_date = datetime.strptime(from_date, dd_mm_yyyy) 111 | to_date = datetime.strptime(to_date, dd_mm_yyyy) 112 | load_days = (to_date - from_date).days 113 | while load_days > 0: 114 | if load_days > 365: 115 | end_date = (from_date + dt.timedelta(364)).strftime(dd_mm_yyyy) 116 | start_date = from_date.strftime(dd_mm_yyyy) 117 | else: 118 | end_date = to_date.strftime(dd_mm_yyyy) 119 | start_date = from_date.strftime(dd_mm_yyyy) 120 | data_df = get_deliverable_position_data(symbol=symbol, from_date=start_date, to_date=end_date) 121 | from_date = from_date + dt.timedelta(365) 122 | load_days = (to_date - from_date).days 123 | if nse_df.empty: 124 | nse_df = data_df 125 | else: 126 | nse_df = pd.concat([nse_df, data_df], ignore_index=True) 127 | return nse_df 128 | 129 | 130 | def india_vix_data(from_date: str = None, to_date: str = None, period: str = None): 131 | """ 132 | get india vix spot data set for the specific time period. 133 | :param from_date: '17-03-2022' ('dd-mm-YYYY') 134 | :param to_date: '17-06-2023' ('dd-mm-YYYY') 135 | :param period: use one {'1D': last day data,'1W': for last 7 days data, 136 | '1M': from last month same date, '6M': last 6 month data, '1Y': from last year same date) 137 | :return: pandas.DataFrame 138 | :raise ValueError if the parameter input is not proper 139 | """ 140 | validate_date_param(from_date, to_date, period) 141 | from_date, to_date = derive_from_and_to_date(from_date=from_date, to_date=to_date, period=period) 142 | nse_df = pd.DataFrame(columns=india_vix_data_column) 143 | from_date = datetime.strptime(from_date, dd_mm_yyyy) 144 | to_date = datetime.strptime(to_date, dd_mm_yyyy) 145 | load_days = (to_date - from_date).days 146 | while load_days > 0: 147 | if load_days > 365: 148 | end_date = (from_date + dt.timedelta(364)).strftime(dd_mm_yyyy) 149 | start_date = from_date.strftime(dd_mm_yyyy) 150 | else: 151 | end_date = to_date.strftime(dd_mm_yyyy) 152 | start_date = from_date.strftime(dd_mm_yyyy) 153 | data_df = get_india_vix_data(from_date=start_date, to_date=end_date) 154 | from_date = from_date + dt.timedelta(365) 155 | load_days = (to_date - from_date).days 156 | if nse_df.empty: 157 | nse_df = data_df 158 | else: 159 | nse_df = pd.concat([nse_df, data_df], ignore_index=True) 160 | return nse_df 161 | 162 | 163 | def index_data(index: str, from_date: str = None, to_date: str = None, period: str = None): 164 | """ 165 | get historical index data set for the specific time period. 166 | apply the index name as per the nse india site 167 | :param index: 'NIFTY 50'/'NIFTY BANK' 168 | :param from_date: '17-03-2022' ('dd-mm-YYYY') 169 | :param to_date: '17-06-2023' ('dd-mm-YYYY') 170 | :param period: use one {'1D': last day data,'1W': for last 7 days data, 171 | '1M': from last month same date, '6M': last 6 month data, '1Y': from last year same date) 172 | :return: pandas.DataFrame 173 | :raise ValueError if the parameter input is not proper 174 | """ 175 | validate_date_param(from_date, to_date, period) 176 | from_date, to_date = derive_from_and_to_date(from_date=from_date, to_date=to_date, period=period) 177 | nse_df = pd.DataFrame(columns=index_data_columns) 178 | from_date = datetime.strptime(from_date, dd_mm_yyyy) 179 | to_date = datetime.strptime(to_date, dd_mm_yyyy) 180 | load_days = (to_date - from_date).days 181 | while load_days > 0: 182 | if load_days > 365: 183 | end_date = (from_date + dt.timedelta(364)).strftime(dd_mm_yyyy) 184 | start_date = from_date.strftime(dd_mm_yyyy) 185 | else: 186 | end_date = to_date.strftime(dd_mm_yyyy) 187 | start_date = from_date.strftime(dd_mm_yyyy) 188 | data_df = get_index_data(index=index, from_date=start_date, to_date=end_date) 189 | from_date = from_date + dt.timedelta(365) 190 | load_days = (to_date - from_date).days 191 | if nse_df.empty: 192 | nse_df = data_df 193 | else: 194 | nse_df = pd.concat([nse_df, data_df], ignore_index=True) 195 | return nse_df 196 | 197 | 198 | def bulk_deal_data(from_date: str = None, to_date: str = None, period: str = None): 199 | """ 200 | get bulk deal data set. 201 | :param from_date: '17-03-2022' ('dd-mm-YYYY') 202 | :param to_date: '17-06-2023' ('dd-mm-YYYY') 203 | :param period: use one {'1D': last day data, 204 | '1W': for last 7 days data, 205 | '1M': from last month same date, 206 | '6M': last 6 month data, 207 | '1Y': from last year same date) 208 | :return: pandas.DataFrame 209 | :raise ValueError if the parameter input is not proper 210 | """ 211 | validate_date_param(from_date, to_date, period) 212 | from_date, to_date = derive_from_and_to_date(from_date=from_date, to_date=to_date, period=period) 213 | nse_df = pd.DataFrame(columns=bulk_deal_data_columns) 214 | from_date = datetime.strptime(from_date, dd_mm_yyyy) 215 | to_date = datetime.strptime(to_date, dd_mm_yyyy) 216 | load_days = (to_date - from_date).days 217 | while load_days > 0: 218 | if load_days > 365: 219 | end_date = (from_date + dt.timedelta(364)).strftime(dd_mm_yyyy) 220 | start_date = from_date.strftime(dd_mm_yyyy) 221 | else: 222 | end_date = to_date.strftime(dd_mm_yyyy) 223 | start_date = from_date.strftime(dd_mm_yyyy) 224 | data_df = get_bulk_deal_data(from_date=start_date, to_date=end_date) 225 | from_date = from_date + dt.timedelta(365) 226 | load_days = (to_date - from_date).days 227 | if nse_df.empty: 228 | nse_df = data_df 229 | else: 230 | nse_df = pd.concat([nse_df, data_df], ignore_index=True) 231 | return nse_df 232 | 233 | 234 | def block_deals_data(from_date: str = None, to_date: str = None, period: str = None): 235 | """ 236 | get block deals data set. 237 | :param from_date: '17-03-2022' ('dd-mm-YYYY') 238 | :param to_date: '17-06-2023' ('dd-mm-YYYY') 239 | :param period: use one {'1D': last day data, 240 | '1W': for last 7 days data, 241 | '1M': from last month same date, 242 | '6M': last 6 month data, 243 | '1Y': from last year same date) 244 | :return: pandas.DataFrame 245 | :raise ValueError if the parameter input is not proper 246 | """ 247 | validate_date_param(from_date, to_date, period) 248 | from_date, to_date = derive_from_and_to_date(from_date=from_date, to_date=to_date, period=period) 249 | nse_df = pd.DataFrame(columns=block_deals_data_columns) 250 | from_date = datetime.strptime(from_date, dd_mm_yyyy) 251 | to_date = datetime.strptime(to_date, dd_mm_yyyy) 252 | load_days = (to_date - from_date).days 253 | while load_days > 0: 254 | if load_days > 365: 255 | end_date = (from_date + dt.timedelta(364)).strftime(dd_mm_yyyy) 256 | start_date = from_date.strftime(dd_mm_yyyy) 257 | else: 258 | end_date = to_date.strftime(dd_mm_yyyy) 259 | start_date = from_date.strftime(dd_mm_yyyy) 260 | data_df = get_block_deals_data(from_date=start_date, to_date=end_date) 261 | from_date = from_date + dt.timedelta(365) 262 | load_days = (to_date - from_date).days 263 | if nse_df.empty: 264 | nse_df = data_df 265 | else: 266 | nse_df = pd.concat([nse_df, data_df], ignore_index=True) 267 | return nse_df 268 | 269 | 270 | def short_selling_data(from_date: str = None, to_date: str = None, period: str = None): 271 | """ 272 | get short selling data set. 273 | :param from_date: '17-03-2022' ('dd-mm-YYYY') 274 | :param to_date: '17-06-2023' ('dd-mm-YYYY') 275 | :param period: use one {'1D': last day data, 276 | '1W': for last 7 days data, 277 | '1M': from last month same date, 278 | '6M': last 6 month data, 279 | '1Y': from last year same date) 280 | :return: pandas.DataFrame 281 | :raise ValueError if the parameter input is not proper 282 | """ 283 | validate_date_param(from_date, to_date, period) 284 | from_date, to_date = derive_from_and_to_date(from_date=from_date, to_date=to_date, period=period) 285 | nse_df = pd.DataFrame(columns=short_selling_data_columns) 286 | from_date = datetime.strptime(from_date, dd_mm_yyyy) 287 | to_date = datetime.strptime(to_date, dd_mm_yyyy) 288 | load_days = (to_date - from_date).days 289 | while load_days > 0: 290 | if load_days > 365: 291 | end_date = (from_date + dt.timedelta(364)).strftime(dd_mm_yyyy) 292 | start_date = from_date.strftime(dd_mm_yyyy) 293 | else: 294 | end_date = to_date.strftime(dd_mm_yyyy) 295 | start_date = from_date.strftime(dd_mm_yyyy) 296 | data_df = get_short_selling_data(from_date=start_date, to_date=end_date) 297 | from_date = from_date + dt.timedelta(365) 298 | load_days = (to_date - from_date).days 299 | if nse_df.empty: 300 | nse_df = data_df 301 | else: 302 | nse_df = pd.concat([nse_df, data_df], ignore_index=True) 303 | return nse_df 304 | 305 | 306 | def bhav_copy_with_delivery(trade_date: str): 307 | """ 308 | get the NSE bhav copy with delivery data as per the traded date 309 | :param trade_date: eg:'20-06-2023' 310 | :return: pandas data frame 311 | """ 312 | trade_date = datetime.strptime(trade_date, dd_mm_yyyy) 313 | use_date = trade_date.strftime(ddmmyyyy) 314 | url = f'https://nsearchives.nseindia.com/products/content/sec_bhavdata_full_{use_date}.csv' 315 | request_bhav = nse_urlfetch(url) 316 | if request_bhav.status_code == 200: 317 | bhav_df = pd.read_csv(BytesIO(request_bhav.content)) 318 | else: 319 | raise FileNotFoundError(f' Data not found, change the trade_date...') 320 | bhav_df.columns = [name.replace(' ', '') for name in bhav_df.columns] 321 | bhav_df['SERIES'] = bhav_df['SERIES'].str.replace(' ', '') 322 | bhav_df['DATE1'] = bhav_df['DATE1'].str.replace(' ', '') 323 | return bhav_df 324 | 325 | 326 | def bhav_copy_equities(trade_date: str): 327 | """ 328 | get new CM-UDiFF Common Bhavcopy Final as per the traded date provided 329 | :param trade_date: 330 | :return: pandas dataframe 331 | """ 332 | trade_date = datetime.strptime(trade_date, dd_mm_yyyy) 333 | url = 'https://nsearchives.nseindia.com/content/cm/BhavCopy_NSE_CM_0_0_0_' 334 | payload = f"{str(trade_date.strftime('%Y%m%d'))}_F_0000.csv.zip" 335 | request_bhav = nse_urlfetch(url + payload) 336 | bhav_df = pd.DataFrame() 337 | if request_bhav.status_code == 200: 338 | zip_bhav = zipfile.ZipFile(BytesIO(request_bhav.content), 'r') 339 | for file_name in zip_bhav.filelist: 340 | if file_name: 341 | bhav_df = pd.read_csv(zip_bhav.open(file_name)) 342 | elif request_bhav.status_code == 403: 343 | raise FileNotFoundError(f' Data not found, change the trade_date...') 344 | # bhav_df = bhav_df[['SYMBOL', 'SERIES', 'OPEN', 'HIGH', 'LOW', 'CLOSE', 'LAST', 'PREVCLOSE', 'TOTTRDQTY', 345 | # 'TOTTRDVAL', 'TIMESTAMP', 'TOTALTRADES']] 346 | return bhav_df 347 | 348 | 349 | def bhav_copy_indices(trade_date: str): 350 | """ 351 | get nse bhav copy as per the traded date provided 352 | :param trade_date: eg:'20-06-2023' 353 | :return: pandas dataframe 354 | """ 355 | trade_date = datetime.strptime(trade_date, dd_mm_yyyy) 356 | url = f"https://nsearchives.nseindia.com/content/indices/ind_close_all_{str(trade_date.strftime('%d%m%Y').upper())}.csv" 357 | file_chk = nse_urlfetch(url) 358 | if file_chk.status_code != 200: 359 | raise FileNotFoundError(f" No data available for : {trade_date}") 360 | try: 361 | bhav_df = pd.read_csv(BytesIO(file_chk.content)) 362 | except Exception as e: 363 | raise FileNotFoundError(f' Bhav copy indices not found for : {trade_date} :: NSE error : {e}') 364 | return bhav_df 365 | 366 | 367 | def bhav_copy_sme(trade_date: str): 368 | """ 369 | get the NSE bhav copy for SME data as per the traded date 370 | :param trade_date: eg:'20-06-2023' 371 | :return: pandas data frame 372 | """ 373 | trade_date = datetime.strptime(trade_date, dd_mm_yyyy) 374 | use_date = trade_date.strftime(ddmmyy) 375 | url = f'https://nsearchives.nseindia.com/archives/sme/bhavcopy/sme{use_date}.csv' 376 | request_bhav = nse_urlfetch(url) 377 | if request_bhav.status_code == 200: 378 | bhav_df = pd.read_csv(BytesIO(request_bhav.content)) 379 | else: 380 | raise FileNotFoundError(f' Data not found, change the trade_date...') 381 | bhav_df.columns = [name.replace(' ', '') for name in bhav_df.columns] 382 | return bhav_df 383 | 384 | 385 | def equity_list(): 386 | """ 387 | get list of all equity available to trade in NSE 388 | :return: pandas data frame 389 | """ 390 | origin_url = "https://nsewebsite-staging.nseindia.com" 391 | url = "https://archives.nseindia.com/content/equities/EQUITY_L.csv" 392 | file_chk = nse_urlfetch(url,origin_url=origin_url) 393 | if file_chk.status_code != 200: 394 | raise FileNotFoundError(f" No data equity list available") 395 | try: 396 | data_df = pd.read_csv(BytesIO(file_chk.content)) 397 | except Exception as e: 398 | raise FileNotFoundError(f' Equity List not found :: NSE error : {e}') 399 | data_df = data_df[['SYMBOL', 'NAME OF COMPANY', ' SERIES', ' DATE OF LISTING', ' FACE VALUE']] 400 | return data_df 401 | 402 | 403 | def fno_equity_list(): 404 | """ 405 | get a dataframe of all listed derivative equity list with the recent lot size to trade 406 | :return: pandas data frame 407 | """ 408 | origin_url = "https://www.nseindia.com/products-services/equity-derivatives-list-underlyings-information" 409 | url = "https://www.nseindia.com/api/underlying-information" 410 | data_obj = nse_urlfetch(url, origin_url=origin_url) 411 | if data_obj.status_code != 200: 412 | raise NSEdataNotFound(f" Resource not available for fno_equity_list") 413 | data_dict = data_obj.json() 414 | data_df = pd.DataFrame(data_dict['data']['UnderlyingList']) 415 | return data_df 416 | 417 | 418 | def fno_index_list(): 419 | """ 420 | get a dataframe of all listed derivative index list with the recent lot size to trade 421 | :return: pandas data frame 422 | """ 423 | origin_url = "https://www.nseindia.com/products-services/equity-derivatives-list-underlyings-information" 424 | url = "https://www.nseindia.com/api/underlying-information" 425 | data_obj = nse_urlfetch(url, origin_url=origin_url) 426 | if data_obj.status_code != 200: 427 | raise NSEdataNotFound(f" Resource not available for fno_equity_index_list") 428 | data_dict = data_obj.json() 429 | data_df = pd.DataFrame(data_dict['data']['IndexList']) 430 | return data_df 431 | 432 | 433 | def nifty50_equity_list(): 434 | """ 435 | list of all equities under NIFTY 50 index 436 | :return: pandas data frame 437 | """ 438 | url = "https://nsearchives.nseindia.com/content/indices/ind_nifty50list.csv" 439 | file_chk = nse_urlfetch(url) 440 | if file_chk.status_code != 200: 441 | raise FileNotFoundError(f" No data equity list available") 442 | try: 443 | data_df = pd.read_csv(BytesIO(file_chk.content)) 444 | except Exception as e: 445 | raise FileNotFoundError(f' equities under NIFTY 50 index not found :: NSE error : {e}') 446 | data_df = data_df[['Company Name', 'Industry', 'Symbol']] 447 | return data_df 448 | 449 | 450 | def niftynext50_equity_list(): 451 | """ 452 | list of all equities under NIFTY NEXT 50 index 453 | :return: pandas data frame 454 | """ 455 | try: 456 | data_df = pd.read_csv("https://archives.nseindia.com/content/indices/ind_niftynext50list.csv") 457 | except Exception as e: 458 | raise FileNotFoundError(f' equities under NIFTY NEXT 50 index not found :: NSE error : {e}') 459 | data_df = data_df[['Company Name', 'Industry', 'Symbol']] 460 | return data_df 461 | 462 | 463 | def niftymidcap150_equity_list(): 464 | """ 465 | list of all equities under NIFTY MIDCAP 150 index 466 | :return: pandas data frame 467 | """ 468 | try: 469 | data_df = pd.read_csv("https://archives.nseindia.com/content/indices/ind_niftymidcap150list.csv") 470 | except Exception as e: 471 | raise FileNotFoundError(f' equities under NIFTY MIDCAP 150 index not found :: NSE error : {e}') 472 | data_df = data_df[['Company Name', 'Industry', 'Symbol']] 473 | return data_df 474 | 475 | 476 | def niftysmallcap250_equity_list(): 477 | """ 478 | list of all equities under NIFTY SMALLCAP 250 index 479 | :return: pandas data frame 480 | """ 481 | try: 482 | data_df = pd.read_csv("https://archives.nseindia.com/content/indices/ind_niftysmallcap250list.csv") 483 | except Exception as e: 484 | raise FileNotFoundError(f' equities under NIFTY SMALLCAP 250 index not found :: NSE error : {e}') 485 | data_df = data_df[['Company Name', 'Industry', 'Symbol']] 486 | return data_df 487 | 488 | 489 | def market_watch_all_indices(): 490 | """ 491 | Market Watch - Indices of the day in data frame 492 | :return: pd.DataFrame 493 | """ 494 | origin_url = "https://nsewebsite-staging.nseindia.com" 495 | url = "https://www.nseindia.com/api/allIndices" 496 | data_json = nse_urlfetch(url, origin_url=origin_url).json() 497 | data_df = pd.DataFrame(data_json['data']) 498 | print(data_df.columns) 499 | return data_df[['key', 'index', 'indexSymbol', 'last', 'variation', 'percentChange', 'open', 'high', 'low', 500 | 'previousClose', 'yearHigh', 'yearLow', 'pe', 'pb', 'dy', 'declines', 'advances', 'unchanged', 501 | 'perChange365d', 'perChange30d', 'previousDay', 'oneWeekAgoVal', 'oneMonthAgoVal', 'oneYearAgoVal']] 502 | 503 | 504 | def fii_dii_trading_activity(): 505 | """ 506 | FII and DII trading activity of the day in data frame 507 | :return: pd.DataFrame 508 | """ 509 | url = "https://www.nseindia.com/api/fiidiiTradeReact" 510 | data_json = nse_urlfetch(url).json() 511 | data_df = pd.DataFrame(data_json) 512 | return data_df 513 | 514 | 515 | def var_begin_day(trade_date: str): 516 | """ 517 | get the VaR Begin Day data as per the traded date 518 | :param trade_date: eg:'20-06-2023' 519 | :return: pandas data frame 520 | """ 521 | trade_date = datetime.strptime(trade_date, dd_mm_yyyy) 522 | use_date = trade_date.strftime(ddmmyyyy) 523 | url = f'https://nsearchives.nseindia.com/archives/nsccl/var/C_VAR1_{use_date}_1.DAT' 524 | request_nse = nse_urlfetch(url) 525 | if request_nse.status_code == 200: 526 | var_df = pd.read_csv(BytesIO(request_nse.content), skiprows=1) 527 | else: 528 | raise FileNotFoundError(f' Data not found, change the trade_date...') 529 | var_df.columns = var_columns 530 | return var_df 531 | 532 | 533 | def var_1st_intra_day(trade_date: str): 534 | """ 535 | get the VaR 1st Intra Day data as per the traded date 536 | :param trade_date: eg:'20-06-2023' 537 | :return: pandas data frame 538 | """ 539 | trade_date = datetime.strptime(trade_date, dd_mm_yyyy) 540 | use_date = trade_date.strftime(ddmmyyyy) 541 | url = f'https://nsearchives.nseindia.com/archives/nsccl/var/C_VAR1_{use_date}_2.DAT' 542 | request_nse = nse_urlfetch(url) 543 | if request_nse.status_code == 200: 544 | var_df = pd.read_csv(BytesIO(request_nse.content), skiprows=1) 545 | else: 546 | raise FileNotFoundError(f' Data not found, change the trade_date...') 547 | var_df.columns = var_columns 548 | return var_df 549 | 550 | 551 | def var_2nd_intra_day(trade_date: str): 552 | """ 553 | get the VaR 2nd Intra Day data as per the traded date 554 | :param trade_date: eg:'20-06-2023' 555 | :return: pandas data frame 556 | """ 557 | trade_date = datetime.strptime(trade_date, dd_mm_yyyy) 558 | use_date = trade_date.strftime(ddmmyyyy) 559 | url = f'https://nsearchives.nseindia.com/archives/nsccl/var/C_VAR1_{use_date}_3.DAT' 560 | request_nse = nse_urlfetch(url) 561 | if request_nse.status_code == 200: 562 | var_df = pd.read_csv(BytesIO(request_nse.content), skiprows=1) 563 | else: 564 | raise FileNotFoundError(f' Data not found, change the trade_date...') 565 | var_df.columns = var_columns 566 | return var_df 567 | 568 | 569 | def var_3rd_intra_day(trade_date: str): 570 | """ 571 | get the VaR 3rd Intra Day data as per the traded date 572 | :param trade_date: eg:'20-06-2023' 573 | :return: pandas data frame 574 | """ 575 | trade_date = datetime.strptime(trade_date, dd_mm_yyyy) 576 | use_date = trade_date.strftime(ddmmyyyy) 577 | url = f'https://nsearchives.nseindia.com/archives/nsccl/var/C_VAR1_{use_date}_4.DAT' 578 | request_nse = nse_urlfetch(url) 579 | if request_nse.status_code == 200: 580 | var_df = pd.read_csv(BytesIO(request_nse.content), skiprows=1) 581 | else: 582 | raise FileNotFoundError(f' Data not found, change the trade_date...') 583 | var_df.columns = var_columns 584 | return var_df 585 | 586 | 587 | def var_4th_intra_day(trade_date: str): 588 | """ 589 | get the VaR 4th Intra Day data as per the traded date 590 | :param trade_date: eg:'20-06-2023' 591 | :return: pandas data frame 592 | """ 593 | trade_date = datetime.strptime(trade_date, dd_mm_yyyy) 594 | use_date = trade_date.strftime(ddmmyyyy) 595 | url = f'https://nsearchives.nseindia.com/archives/nsccl/var/C_VAR1_{use_date}_5.DAT' 596 | request_nse = nse_urlfetch(url) 597 | if request_nse.status_code == 200: 598 | var_df = pd.read_csv(BytesIO(request_nse.content), skiprows=1) 599 | else: 600 | raise FileNotFoundError(f' Data not found, change the trade_date...') 601 | var_df.columns = var_columns 602 | return var_df 603 | 604 | 605 | def var_end_of_day(trade_date: str): 606 | """ 607 | get the VaR End of Day data as per the traded date 608 | :param trade_date: eg:'20-06-2023' 609 | :return: pandas data frame 610 | """ 611 | trade_date = datetime.strptime(trade_date, dd_mm_yyyy) 612 | use_date = trade_date.strftime(ddmmyyyy) 613 | url = f'https://nsearchives.nseindia.com/archives/nsccl/var/C_VAR1_{use_date}_6.DAT' 614 | request_nse = nse_urlfetch(url) 615 | if request_nse.status_code == 200: 616 | var_df = pd.read_csv(BytesIO(request_nse.content), skiprows=1) 617 | else: 618 | raise FileNotFoundError(f' Data not found, change the trade_date...') 619 | var_df.columns = var_columns 620 | return var_df 621 | 622 | 623 | def sme_bhav_copy(trade_date: str): 624 | """ 625 | get the SME bhav copy data as per the traded date 626 | :param trade_date: eg:'20-06-2023' 627 | :return: pandas data frame 628 | """ 629 | trade_date = datetime.strptime(trade_date, dd_mm_yyyy) 630 | use_date = trade_date.strftime(ddmmyy) 631 | url = f'https://nsearchives.nseindia.com/archives/sme/bhavcopy/sme{use_date}.csv' 632 | request_bhav = nse_urlfetch(url) 633 | if request_bhav.status_code == 200: 634 | bhav_df = pd.read_csv(BytesIO(request_bhav.content)) 635 | else: 636 | raise FileNotFoundError(f' Data not found, change the trade_date...') 637 | bhav_df.columns = [name.replace(' ', '') for name in bhav_df.columns] 638 | return bhav_df 639 | 640 | 641 | def sme_band_complete(trade_date: str): 642 | """ 643 | get the SME Band Complete data as per the traded date 644 | :param trade_date: eg:'20-06-2023' 645 | :return: pandas data frame 646 | """ 647 | trade_date = datetime.strptime(trade_date, dd_mm_yyyy) 648 | use_date = trade_date.strftime(ddmmyyyy) 649 | url = f'https://nsearchives.nseindia.com/sme/content/price_band/archieves/sme_bands_complete_{use_date}.csv' 650 | request_sme = nse_urlfetch(url) 651 | if request_sme.status_code == 200: 652 | sme_df = pd.read_csv(BytesIO(request_sme.content)) 653 | else: 654 | raise FileNotFoundError(f' Data not found, change the trade_date...') 655 | sme_df.columns = [name.replace(' ', '') for name in sme_df.columns] 656 | return sme_df 657 | 658 | 659 | def week_52_high_low_report(trade_date: str): 660 | """ 661 | get the 52-Week High Low Report data as per the traded date 662 | :param trade_date: eg:'20-06-2023' 663 | :return: pandas data frame 664 | """ 665 | trade_date = datetime.strptime(trade_date, dd_mm_yyyy) 666 | use_date = trade_date.strftime(ddmmyyyy) 667 | url = f'https://nsearchives.nseindia.com/content/CM_52_wk_High_low_{use_date}.csv' 668 | request_nse = nse_urlfetch(url) 669 | if request_nse.status_code == 200: 670 | high_low_df = pd.read_csv(BytesIO(request_nse.content), skiprows=2) 671 | else: 672 | raise FileNotFoundError(f' Data not found, change the trade_date...') 673 | high_low_df.columns = [name.replace(' ', '') for name in high_low_df.columns] 674 | return high_low_df 675 | 676 | 677 | def financial_results_for_equity(from_date: str = None, 678 | to_date: str = None, 679 | period: str = None, 680 | fo_sec: bool = False, 681 | fin_period: str = 'Quarterly'): 682 | 683 | """ 684 | get audited and un-auditable financial results for equities. as per 685 | https://www.nseindia.com/companies-listing/corporate-filings-financial-results 686 | :param fin_period: Quaterly/ Half-Yearly/ Annual/ Others 687 | :param fo_sec: True/False 688 | :param from_date: '17-03-2022' ('dd-mm-YYYY') 689 | :param to_date: '17-06-2023' ('dd-mm-YYYY') 690 | :param period: use one {'1D': last day data, 691 | '1W': for last 7 days data, 692 | '1M': from last month same date, 693 | '6M': last 6 month data, 694 | '1Y': from last year same date) 695 | :return: pandas.DataFrame 696 | :raise ValueError if the parameter input is not proper 697 | """ 698 | master_data_df, headers, ns, keys_to_extract = get_financial_results_master(from_date, to_date, period, 699 | fo_sec, fin_period) 700 | fin_df, df = pd.DataFrame(), pd.DataFrame() 701 | for row in master_data_df.itertuples(index=False): 702 | try: 703 | # Fetch the XML content 704 | response_ = requests.get(row.xbrl, headers=headers) 705 | response_.raise_for_status() # Check for HTTP errors 706 | 707 | # Parse the XML content 708 | root = ET.fromstring(response_.content) 709 | 710 | # Extract values 711 | extracted_data = {} 712 | for key in keys_to_extract: 713 | elem_ = root.find(f".//in-bse-fin:{key}", ns) 714 | extracted_data[key] = elem_.text if elem_ is not None else None 715 | 716 | # Convert to Pandas DataFrame 717 | df = pd.DataFrame([extracted_data]) 718 | except requests.exceptions.RequestException as e: 719 | raise requests.exceptions.RequestException(f"Request failed: {e}") from e 720 | except ET.ParseError as e: 721 | raise ET.ParseError(f"XML parsing failed: {e}") from e 722 | except Exception as e: 723 | raise RuntimeError(f"An error occurred: {e}") from e 724 | 725 | if fin_df.empty: 726 | fin_df = df 727 | else: 728 | fin_df = pd.concat([fin_df, df], ignore_index=True) 729 | return fin_df 730 | 731 | 732 | def corporate_bond_trade_report(trade_date: str): 733 | """ 734 | get the NSE corporate bond trade report as per the traded date 735 | :param trade_date: eg:'20-06-2023' 736 | :return: pandas data frame 737 | """ 738 | trade_date = datetime.strptime(trade_date, dd_mm_yyyy) 739 | use_date = trade_date.strftime(ddmmyy) 740 | url = f'https://nsearchives.nseindia.com/archives/equities/corpbond/corpbond{use_date}.csv' 741 | request_bhav = nse_urlfetch(url) 742 | if request_bhav.status_code == 200: 743 | bond_df = pd.read_csv(BytesIO(request_bhav.content)) 744 | else: 745 | raise FileNotFoundError(f' Data not found, change the trade_date...') 746 | bond_df.columns = [name.replace(' ', '') for name in bond_df.columns] 747 | bond_df['SERIES'] = bond_df['SERIES'].str.replace(' ', '') 748 | return bond_df 749 | 750 | 751 | def pe_ratio(trade_date: str): 752 | """ 753 | get the NSE pe ratio for all NSE equities data as per the traded date 754 | :param trade_date: eg:'20-06-2023' 755 | :return: pandas data frame 756 | """ 757 | trade_date = datetime.strptime(trade_date, dd_mm_yyyy) 758 | use_date = trade_date.strftime(ddmmyy) 759 | url = f'https://nsearchives.nseindia.com/content/equities/peDetail/PE_{use_date}.csv' 760 | request_bhav = nse_urlfetch(url) 761 | if request_bhav.status_code == 200: 762 | pe_df = pd.read_csv(BytesIO(request_bhav.content)) 763 | else: 764 | raise FileNotFoundError(f' Data not found, change the trade_date...') 765 | pe_df.columns = [name.replace(' ', '') for name in pe_df.columns] 766 | return pe_df 767 | 768 | 769 | def corporate_actions_for_equity(from_date: str = None, 770 | to_date: str = None, 771 | period: str = None, 772 | fno_only: bool = False): 773 | 774 | """ 775 | get corporate actions for equities as per 776 | https://www.nseindia.com/companies-listing/corporate-filings-actions 777 | :param fno_only: True/False 778 | :param from_date: '17-03-2022' ('dd-mm-YYYY') 779 | :param to_date: '17-06-2023' ('dd-mm-YYYY') 780 | :param period: use one {'1D': last day data, 781 | '1W': for last 7 days data, 782 | '1M': from last month same date, 783 | '6M': last 6 month data, 784 | '1Y': from last year same date) 785 | :return: pandas.DataFrame 786 | :raise ValueError if the parameter input is not proper 787 | """ 788 | validate_date_param(from_date, to_date, period) 789 | from_date, to_date = derive_from_and_to_date(from_date=from_date, to_date=to_date, period=period) 790 | origin_url = "https://www.nseindia.com/companies-listing/corporate-filings-actions" 791 | url_ = "https://www.nseindia.com/api/corporates-corporateactions?index=equities&" 792 | if fno_only: 793 | payload = f'from_date={from_date}&to_date={to_date}&fo_sec=true' 794 | else: 795 | payload = f'from_date={from_date}&to_date={to_date}' 796 | data_text = nse_urlfetch(url_ + payload, origin_url=origin_url) 797 | if data_text.status_code != 200: 798 | raise NSEdataNotFound(f" Resource not available for financial data with these parameters") 799 | json_str = data_text.content.decode("utf-8") 800 | data_list = json.loads(json_str) 801 | master_data_df = pd.DataFrame(data_list) 802 | master_data_df.columns = [name.replace(' ', '') for name in master_data_df.columns] 803 | return master_data_df 804 | 805 | 806 | def event_calendar_for_equity(from_date: str = None, 807 | to_date: str = None, 808 | period: str = None, 809 | fno_only: bool = False): 810 | 811 | """ 812 | get event calendar for equities as per 813 | https://www.nseindia.com/companies-listing/corporate-filings-event-calendar 814 | :param fno_only: True/False 815 | :param from_date: '17-03-2022' ('dd-mm-YYYY') 816 | :param to_date: '17-06-2023' ('dd-mm-YYYY') 817 | :param period: use one {'1D': last day data, 818 | '1W': for last 7 days data, 819 | '1M': from last month same date, 820 | '6M': last 6 month data, 821 | '1Y': from last year same date) 822 | :return: pandas.DataFrame 823 | :raise ValueError if the parameter input is not proper 824 | """ 825 | validate_date_param(from_date, to_date, period) 826 | from_date, to_date = derive_from_and_to_date(from_date=from_date, to_date=to_date, period=period) 827 | origin_url = "https://www.nseindia.com/companies-listing/corporate-filings-event-calendar" 828 | url_ = "https://www.nseindia.com/api/event-calendar?index=equities&" 829 | if fno_only: 830 | payload = f'from_date={from_date}&to_date={to_date}&fo_sec=true' 831 | else: 832 | payload = f'from_date={from_date}&to_date={to_date}' 833 | data_text = nse_urlfetch(url_ + payload, origin_url=origin_url) 834 | if data_text.status_code != 200: 835 | raise NSEdataNotFound(f" Resource not available for financial data with these parameters") 836 | json_str = data_text.content.decode("utf-8") 837 | data_list = json.loads(json_str) 838 | master_data_df = pd.DataFrame(data_list) 839 | master_data_df.columns = [name.replace(' ', '') for name in master_data_df.columns] 840 | return master_data_df 841 | 842 | 843 | def top_gainers_or_losers(to_get: str = 'gainers'): 844 | """ 845 | get top gainers or losers on live market, after market hour it will get as per last traded value 846 | :param to_get: gainers/loosers 847 | :return: pandas.DataFrame 848 | :raise ValueError if the parameter input is not proper 849 | """ 850 | static_options_list = ['gainers', 'loosers'] 851 | validate_param_from_list(to_get, static_options_list) 852 | data_json = get_top_gainers_or_losers(to_get) 853 | legends_dict = {item[0]: item[1] for item in data_json['legends']} 854 | gainers_losers_df = pd.DataFrame() 855 | for i in legends_dict.keys(): 856 | data_df = pd.DataFrame(data_json[i]['data']) 857 | data_df['legend'] = i 858 | if gainers_losers_df.empty: 859 | gainers_losers_df = data_df 860 | else: 861 | gainers_losers_df = pd.concat([gainers_losers_df, data_df]) 862 | return gainers_losers_df 863 | 864 | 865 | def most_active_equities(fetch_by: str = 'value'): 866 | """ 867 | to get most active equities fetched by value/volume in live market, after market hour it will get as per last traded value 868 | link : https://www.nseindia.com/market-data/most-active-equities 869 | :param fetch_by: select any volume/value 870 | :return: pandas dataframe 871 | """ 872 | static_options_list = ['volume', 'value'] 873 | validate_param_from_list(fetch_by, static_options_list) 874 | origin_url = "https://www.nseindia.com/market-data/most-active-equities" 875 | url = f"https://www.nseindia.com/api/live-analysis-most-active-securities?index={fetch_by}" 876 | try: 877 | data_json = nse_urlfetch(url, origin_url=origin_url).json() 878 | data_df = pd.DataFrame(data_json['data']) 879 | except Exception as e: 880 | raise NSEdataNotFound(f" Resource not available MSG: {e}") 881 | return data_df 882 | 883 | 884 | def total_traded_stocks(): 885 | """ 886 | to get all total traded stocks detail in live market, after market hour it will get as per last traded value 887 | summary_dict - has the live market summary for the stocks in dictionary format 888 | detail_df - has all detail available in the current market in dataframe format 889 | link : https://www.nseindia.com/market-data/stocks-traded 890 | :return: summary_dict, detail_df 891 | """ 892 | origin_url = "https://www.nseindia.com/market-data/stocks-traded" 893 | url = f"https://www.nseindia.com/api/live-analysis-stocksTraded" 894 | try: 895 | data_json = nse_urlfetch(url, origin_url=origin_url).json() 896 | summary_dict = data_json['total']['count'] 897 | detail_df = pd.DataFrame(data_json['total']['data']) 898 | except Exception as e: 899 | raise NSEdataNotFound(f" Resource not available MSG: {e}") 900 | return summary_dict, detail_df 901 | 902 | 903 | # if __name__ == '__main__': 904 | # data = pe_ratio(trade_date='11-09-2024') # trade_date='11-09-2024' 905 | # data = index_data(index='NIFTY 50', period='1W') 906 | # data = block_deals_data(period='1W') 907 | # data = bulk_deal_data(period='1W') 908 | # data = india_vix_data(period='1W') 909 | # data = short_selling_data(period='1W') 910 | # data = index_data(index='NIFTY 50', from_date='21-10-2024', to_date='30-10-2024') 911 | # data = deliverable_position_data(symbol='SBIN', from_date='23-03-2024', to_date='23-06-2024') 912 | # data = market_watch_all_indices() 913 | # data = fno_equity_list() 914 | # data = price_volume_and_deliverable_position_data(symbol='SBIN', from_date='23-03-2024', to_date='23-06-2024') 915 | # data = price_volume_and_deliverable_position_data(symbol='SBIN', period='1M') 916 | # data = price_volume_data(symbol='SBIN', from_date='20-06-2023', to_date='20-07-2023') 917 | # data = financial_results_for_equity(from_date='11-03-2025', to_date='16-03-2025', fo_sec=True, 918 | # fin_period='Quarterly') 919 | # data = corporate_actions_for_equity(period='6M', fno_only=False) 920 | # data = event_calendar_for_equity(period='1M', fno_only=False) 921 | # data = sme_band_complete(trade_date='11-03-2025') 922 | # data = top_gainers_or_losers('loosers') # gainers/losers 923 | # data = most_active_equities(fetch_by='volume') # value/volume 924 | # data = total_traded_stocks() 925 | # data.to_csv(fr'C:\Ruchi Tanmay\Stock Market\Data Analysis\Final Data\data.csv') 926 | 927 | # data = niftymidcap150_equity_list() 928 | # print(data) 929 | # print(data.info()) 930 | # ----------------------------------------------------- 931 | 932 | --------------------------------------------------------------------------------