Skip to content

Instantly share code, notes, and snippets.

@bpsagar
Last active April 11, 2024 15:33
Show Gist options
  • Save bpsagar/a14d2f4fc3ab17cc82b1f6c0acd8549c to your computer and use it in GitHub Desktop.
Save bpsagar/a14d2f4fc3ab17cc82b1f6c0acd8549c to your computer and use it in GitHub Desktop.
A simple script to get the price of a stock in NSE market and price of mutual funds (India)
"""
Usage:
$ import mf
$ mf.get_price('INF200K01VK1') # pass ISIN of the mutual fund
> 1126.55
"""
import os
import requests
import tempfile
from datetime import datetime
from typing import Optional
AMFI_URL = 'https://www.amfiindia.com/spages/NAVAll.txt?'
AMFI_NAV_COLUMN_NAME = 'Net Asset Value'
def _download_file(filepath: str) -> bool:
date = datetime.now().date()
try:
response = requests.get(AMFI_URL)
except:
return False
with open(filepath, 'wb') as fd:
fd.write(response.content)
return True
def _extract_price(symbol: str, filepath: str) -> Optional[float]:
with open(filepath, 'r') as fd:
lines = fd.readlines()
index = lines[0].split(';').index(AMFI_NAV_COLUMN_NAME)
prices = {}
for line in lines[1:]:
items = line.split(';')
if len(items) < 6:
# It is not a line with information we need
continue
try:
price = float(items[index])
except:
# Sometimes price is "N.A."
continue
# There are 2 columns for symbols
if items[1] != '-':
prices[items[1]] = price
if items[2] != '-':
prices[items[2]] = price
return prices.get(symbol)
def get_price(symbol: str) -> Optional[float]:
filename = '{}-mf-prices.txt'.format(datetime.now().date().isoformat())
filepath = os.path.join(tempfile.gettempdir(), filename)
if not os.path.exists(filepath):
success = _download_file(filepath=filepath)
if not success:
return None
return _extract_price(symbol=symbol, filepath=filepath)
"""
Usage:
$ import nse
$ nse.get_price('NIFTYBEES') # pass symbol of the stock
> 186.18
"""
import os
import requests
import tempfile
from datetime import datetime, timedelta
from typing import Optional
NSE_DATA_URL = 'https://archives.nseindia.com/products/content/sec_bhavdata_full_{}.csv'
NSE_DATE_FORMAT = '%d%m%Y'
NSE_PRICE_COLUMN_NAME = 'CLOSE_PRICE'
def _download_file(filepath: str) -> bool:
date = datetime.now().date()
response = None
for retry in range(5):
url = NSE_DATA_URL.format(date.strftime(NSE_DATE_FORMAT))
try:
response = requests.get(url, timeout=2)
break
except:
pass
date = date - timedelta(days=1)
if response:
with open(filepath, 'wb') as fd:
fd.write(response.content)
return True
return False
def _extract_price(symbol: str, filepath: str) -> Optional[float]:
with open(filepath, 'r') as fd:
lines = fd.readlines()
index = lines[0].split(', ').index(NSE_PRICE_COLUMN_NAME)
prices = {}
for line in lines[1:]:
s = line.split(', ')[0]
price = line.split(', ')[index]
prices[s] = float(price)
return prices.get(symbol)
def get_price(symbol: str) -> Optional[float]:
filename = '{}-equity-prices.csv'.format(datetime.now().date().isoformat())
filepath = os.path.join(tempfile.gettempdir(), filename)
if not os.path.exists(filepath):
success = _download_file(filepath=filepath)
if not success:
return None
return _extract_price(symbol=symbol, filepath=filepath)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment