3dcc80e729
git-subtree-dir: utils_v2 git-subtree-split: 584dbfca44919368a858b02e0b45d503d7ccc874
306 lines
13 KiB
Python
306 lines
13 KiB
Python
"""
|
|
|
|
AUTHOR:
|
|
|
|
Khushal P Soonderji
|
|
|
|
DATE:
|
|
|
|
Thursday, 5th Dec., 2024
|
|
|
|
OBJECTIVE:
|
|
|
|
To provide a way to retrieve pre-market data from NSE. This is typically available by 9:10 AM.
|
|
|
|
NOTE: This method involves web scraping. It is good for proof-of-concept development, but it is recommended that
|
|
more professional data-sources be used when the product starts becoming mature.
|
|
|
|
REFERENCES:
|
|
|
|
N/A
|
|
|
|
DOWNLOADS:
|
|
|
|
N/A
|
|
|
|
"""
|
|
|
|
|
|
# *****************************************************************************************************************
|
|
# ***** ****
|
|
# *** IMPORT ***
|
|
# ***** ****
|
|
# *****************************************************************************************************************
|
|
|
|
|
|
# To make sibling directories accessible for imports:
|
|
import sys
|
|
sys.path.append(".")
|
|
sys.path.append("..")
|
|
|
|
# System-level activities:
|
|
import io
|
|
|
|
# My utils:
|
|
from utils_v2.string import json
|
|
from utils_v2.string import regex
|
|
from utils_v2.date_time import date_time
|
|
|
|
# NSE-related utils:
|
|
from utils_v2.nse.controllers.base import AsyncNSEBase
|
|
from utils_v2.nse.models.api_call import NSEApiResponse
|
|
from utils_v2.nse.models.pre_market import NSEPreMarketData, NSEPreMarketSymbol
|
|
|
|
# To make REST-ful API calls:
|
|
import httpx
|
|
|
|
# To work with date and time:
|
|
import datetime
|
|
|
|
# To work with datatypes:
|
|
from typing import Any, List
|
|
|
|
# For asynchronous activities:
|
|
import asyncio
|
|
|
|
|
|
# *****************************************************************************************************************
|
|
# ***** ****
|
|
# *** MACROS / ONE-TIME INIT ***
|
|
# ***** ****
|
|
# *****************************************************************************************************************
|
|
|
|
|
|
# --- Nothing Yet
|
|
|
|
|
|
# *****************************************************************************************************************
|
|
# ***** ****
|
|
# *** VARIABLES ***
|
|
# ***** ****
|
|
# *****************************************************************************************************************
|
|
|
|
|
|
# --- Nothing Yet
|
|
|
|
|
|
# *****************************************************************************************************************
|
|
# ***** ****
|
|
# *** FUNCTIONS ***
|
|
# ***** ****
|
|
# *****************************************************************************************************************
|
|
|
|
|
|
class NSEPreMarket(AsyncNSEBase):
|
|
|
|
# Symbol names:
|
|
PRE_MARKET_KEY_NIFTY = "NIFTY"
|
|
PRE_MARKET_KEY_BANK_NIFTY = "BANKNIFTY"
|
|
PRE_MARKET_KEY_SME = "SME"
|
|
PRE_MARKET_KEY_FO = "FO"
|
|
PRE_MARKET_KEY_OTHERS = "OTHERS"
|
|
PRE_MARKET_KEY_ALL = "ALL"
|
|
|
|
def __init__(
|
|
self,
|
|
http_client: httpx.AsyncClient,
|
|
cookies_refresh_interval: int | float = 300,
|
|
debug = True,
|
|
debug_prefix = "NSE (PreMkt.) | ",
|
|
debug_only_errors = True
|
|
):
|
|
|
|
# Pass on the initialization to the parent:
|
|
super().__init__(
|
|
base_url = r"https://www.nseindia.com/market-data/pre-open-market-cm-and-emerge-market",
|
|
data_url = r"https://www.nseindia.com/api/market-data-pre-open",
|
|
http_client = http_client,
|
|
cookies_refresh_interval = cookies_refresh_interval,
|
|
debug = debug,
|
|
debug_prefix = debug_prefix,
|
|
debug_only_errors = debug_only_errors
|
|
)
|
|
|
|
async def get_data(
|
|
self,
|
|
key: str,
|
|
return_raw: bool = False,
|
|
refresh_cookies: bool = True,
|
|
force_refresh_cookies: bool = False,
|
|
retry_count: int = 1,
|
|
backoff_seconds: int | float = 0.5,
|
|
backoff_multiplier: float = 1.1
|
|
) -> NSEApiResponse:
|
|
|
|
"""
|
|
To get the data of the pre-open market trading. Useful for finding gaps and expected unusual activity in the
|
|
trading hours.
|
|
:param key: The type of pre-market data that you want. Choose from the class variables.
|
|
:param return_raw: Whether you want the raw JSON from NSE or you want it formatted.
|
|
:param refresh_cookies: Whether, or not, you would like to refresh the cookies.
|
|
:param force_refresh_cookies: If set to True, cookies will be refreshed even if not timed out. If set to False,
|
|
cookies will be refreshed only when the interval passed to the constructor has elapsed since the last
|
|
successful refresh.
|
|
:param retry_count: The no. of times to try to get the data from the API.
|
|
:param backoff_seconds: The delay between unsuccessful API calls.
|
|
:param backoff_multiplier: The multiplier to add to the delay to change delay.
|
|
:return: The raw or formatted event calendar data in the 'data' field of the response model.
|
|
"""
|
|
|
|
# Make the API call:
|
|
api_response = await self.get(
|
|
params = {"key": key},
|
|
refresh_cookies = refresh_cookies,
|
|
force_refresh_cookies = force_refresh_cookies,
|
|
retry_count = retry_count,
|
|
backoff_seconds = backoff_seconds,
|
|
backoff_multiplier = backoff_multiplier
|
|
)
|
|
|
|
# If the API call was successful:
|
|
if api_response.httpCode in [200]:
|
|
api_response.success = True
|
|
if return_raw: api_response.data = await api_response.get_json()
|
|
else:
|
|
try: api_response.data = self.format_data(
|
|
raw_json = await api_response.get_json(),
|
|
key = key,
|
|
timestamp = date_time.get_current_utc_date_time(as_string = False),
|
|
raise_exception = True
|
|
)
|
|
except Exception as exception:
|
|
api_response.exception = exception
|
|
api_response.success = False
|
|
|
|
# Done here:
|
|
return api_response
|
|
|
|
@staticmethod
|
|
def format_data(
|
|
raw_json: dict,
|
|
key: str = None,
|
|
timestamp: datetime.datetime = None,
|
|
raise_exception: bool = False
|
|
) -> NSEPreMarketData | None:
|
|
|
|
"""
|
|
We format the data here to be able to retrieve it properly later.
|
|
:param raw_json: The raw data as scraped from NSE.
|
|
:param key: A choice between "NIFTY", "BANKNIFTY", "SME", "FO", "OTHERS", "ALL".
|
|
:param timestamp: The timestamp at which the data was scraped. This shall be useful for data retrieval from the
|
|
database, later.
|
|
:param raise_exception: If set to True, any exception will be propagated. If set to False, any exception will be
|
|
suppressed internally.
|
|
:return: The formatted data if successful, else None.
|
|
"""
|
|
|
|
# Can't do anything if the chain itself is null:
|
|
if raw_json is None: return raw_json
|
|
|
|
# Start by assuming failure:
|
|
formatted_data = None
|
|
|
|
# Ensure that we've got a proper timestamp:
|
|
if timestamp is None: timestamp = date_time.get_current_utc_date_time(as_string = False)
|
|
|
|
try:
|
|
|
|
# Start by extracting basic data:
|
|
formatted_data = {
|
|
"scrapeTs": timestamp,
|
|
"ts": date_time.to_timezone(
|
|
date_time.as_if_timezone(
|
|
date_time.parse_date_time(
|
|
input_value = raw_json["timestamp"],
|
|
date_formats = ["%d-%b-%Y %H:%M:%S"]
|
|
),
|
|
timezone = date_time.TIMEZONE_IST
|
|
),
|
|
timezone = date_time.TIMEZONE_UTC
|
|
),
|
|
"key": key,
|
|
"advances": raw_json["advances"],
|
|
"declines": raw_json["declines"],
|
|
"unchanged": raw_json["unchanged"],
|
|
"totalMarketCap": raw_json["totalmarketcap"],
|
|
"totalTradedValue": raw_json["totalTradedValue"],
|
|
"totalTradedVolume": raw_json["totalTradedVolume"],
|
|
"symbols": []
|
|
}
|
|
|
|
# Now we iterate through the symbol-wise data and extract what we need:
|
|
for raw_symbol_data in raw_json["data"]:
|
|
raw_symbol_metadata = raw_symbol_data["metadata"]
|
|
raw_symbol_detail = raw_symbol_data["detail"]["preOpenMarket"]
|
|
market_cap = regex.find_first(text = str(raw_symbol_metadata["marketCap"]), pattern = r"[\d,]+\.?[\d,]*")
|
|
formatted_data["symbols"].append({
|
|
"symbol": raw_symbol_metadata["symbol"],
|
|
"ffmc": float(market_cap) if market_cap else None,
|
|
"trigger": raw_symbol_metadata["purpose"],
|
|
"yearHigh": raw_symbol_metadata["yearHigh"],
|
|
"yearLow": raw_symbol_metadata["yearLow"],
|
|
"prevClose": raw_symbol_metadata["previousClose"],
|
|
"preMarketPrice": raw_symbol_metadata["iep"],
|
|
"chg": raw_symbol_metadata["change"],
|
|
"pChg": raw_symbol_metadata["pChange"],
|
|
"totalTradedVolume": raw_symbol_detail["totalTradedVolume"],
|
|
"totalBuyVolume": raw_symbol_detail["totalBuyQuantity"],
|
|
"totalSellVolume": raw_symbol_detail["totalSellQuantity"],
|
|
})
|
|
|
|
# Data sorting (descending order of percent change):
|
|
formatted_data["symbols"] = sorted(
|
|
formatted_data["symbols"],
|
|
key = lambda x: x["pChg"],
|
|
reverse = True
|
|
)
|
|
|
|
# Model the data:
|
|
formatted_data = NSEPreMarketData(**formatted_data)
|
|
|
|
# If something goes wrong:
|
|
except Exception as exception:
|
|
formatted_data = None
|
|
if raise_exception: raise
|
|
|
|
# Done here:
|
|
return formatted_data
|
|
|
|
|
|
# *****************************************************************************************************************
|
|
# ***** ****
|
|
# *** MAIN PROGRAM ***
|
|
# ***** ****
|
|
# *****************************************************************************************************************
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
async def main():
|
|
|
|
# Create an HTTP client:
|
|
test_client = httpx.AsyncClient(
|
|
limits = httpx.Limits(
|
|
max_connections = 100, # ............ Maximum number of connections allowed in the pool.
|
|
max_keepalive_connections = 50, # ... Maximum number of connections that can be kept alive.
|
|
),
|
|
timeout = httpx.Timeout(
|
|
pool = 120.0, # .... Time to wait for a free connection from the pool.
|
|
connect = 2.5, # ... Time to wait for establishing a connection to the server.
|
|
write = 10.0, # .... Time to wait for sending data.
|
|
read = 9.9 # ....... Time to wait for receiving data.
|
|
)
|
|
)
|
|
|
|
# Create an instance of the scraper, and refresh its cookies:
|
|
my_nse = NSEPreMarket(http_client = test_client)
|
|
|
|
# Get and show the data:
|
|
api_response = await my_nse.get_data(key = my_nse.PRE_MARKET_KEY_FO, return_raw = False)
|
|
print("SUMMARY:", api_response.to_markdown(), "\n---\n\n")
|
|
if api_response.success: print("PRE-MARKET DATA:", json.to_string(api_response.data, default = str))
|
|
if api_response.exception: raise api_response.exception
|
|
print("COUNT:", len(api_response.data.symbols))
|
|
|
|
asyncio.run(main())
|