Skip to content

Commit

Permalink
CSV and Nonworking Days
Browse files Browse the repository at this point in the history
  • Loading branch information
pyFrappe committed Apr 24, 2021
0 parents commit a6c073a
Show file tree
Hide file tree
Showing 10 changed files with 288 additions and 0 deletions.
17 changes: 17 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
70 changes: 70 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# NEPSE
## _The Last Nepse Module You'll Ever Need_

Nepse is a realtime nepse scraper which communicates with newweb.nepalstock.com.np, to fetch and return required stats.


## Features

- Get Brokers
- Get Realtime Prices
- Make Charts and Many More



## Installation

Nepse requires [python3 and pip](http://python.org/) to install and run.

```sh
pip install nepse
```


## Plugins

Nepse is currently extended with the following plugins.
Instructions on how to use them in your own application are linked below.

| Plugin | LINK |
| ------ | ------ |
| Matplotlib | https://matplotlib.org/|
| Requests | https://pypi.org/project/requests/ |
| Pandas (For Next Update) | https://pandas.pydata.org/ |

## Usage


```py
from nepse import NEPSE
init = NEPSE()

#GET ALL REGISTERED BROKERS
brokers = init.brokers()

#GET ALL NEWS & ALERTS Published By NEPSE on Newweb
news= init.alerts()

#Check IF MARKET IS OPEN
isOpen = init.isOpen() #Returns TRUE IF market is open

#Check live price of specific scrip or get all prices
allPrices = init.todayPrice()
cghPrice = init.todayPrice('CGH') #returns information for CGH

#CHARTS
chartHistory = init.getChartHistory('CGH') #Get History Prices for CGH
chartHistoryButFiltered = init.getChartHistory('CGH',start_date='2021-03-04',end_date='2021-03-07')

makeChart= init.createChart('CGH',theme='dark',high=False,low=False)#returns abspath of chart saved

csv = init.saveCSV('CGH',start_date='2021-02-07')#filename,start_date and end_date are optional


```


## License

MIT

1 change: 1 addition & 0 deletions nepse/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from nepse.stonk import NEPSE
Binary file added nepse/__pycache__/__init__.cpython-38.pyc
Binary file not shown.
Binary file added nepse/__pycache__/__init__.cpython-39.pyc
Binary file not shown.
Binary file added nepse/__pycache__/nepse.cpython-38.pyc
Binary file not shown.
Binary file added nepse/__pycache__/stonk.cpython-38.pyc
Binary file not shown.
Binary file added nepse/__pycache__/stonk.cpython-39.pyc
Binary file not shown.
178 changes: 178 additions & 0 deletions nepse/stonk.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
import requests
import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime,timedelta
import time
import os

class NEPSE:

def __init__(self):
self.headers= {
'authority': 'newweb.nepalstock.com.np',
'sec-ch-ua': '^\\^Google',
'accept': 'application/json, text/plain, */*',
'sec-ch-ua-mobile': '?0',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36',
'sec-fetch-site': 'same-origin',
'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',
'referer': 'https://newweb.nepalstock.com.np/',
'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
}
self.host = 'https://newweb.nepalstock.com.np/api/'
self.securities = requests.get(self.host+'nots/securityDailyTradeStat/58',headers=self.headers).json()
pass


def dateFilter(self,working_date,data):
"""
Function to return next working day , if the date provided is non-working day.
Returns either first or last date if the date provided is too ahead or too back.
"""

all_dates =[date['businessDate'] for date in data]
if working_date in all_dates:
return working_date
else:
i=0
while 1:

date=datetime.strptime(working_date,'%Y-%m-%d')
new_date=str(date+timedelta(days=i)).split(' ')[0]
if new_date in all_dates:
return new_date
i+=1
if i>=7:
month = working_date.split('-')[1]
year = working_date.split('-')[0]
day=working_date.split('-')[-1]
if year > all_dates[-1].split('-')[0] and month > all_dates[-1].split('-')[1]:
return all_dates[-1]
return all_dates[0]


def isOpen(self):
"""
Returns True if the market is Open .
"""
response = requests.get(self.host+'/nots/nepse-data/market-open', headers=self.headers).json()
if response['isOpen'] !='CLOSE':
return True
return False

def brokers(self):
"""
Returns all the registered brokers along with tms url and other information
"""
resp = requests.get(self.host+'nots/member?&size=500',headers=self.headers).json()
return resp

def alerts(self):
"""
returns alerts and news published by
"""
resp = requests.get(self.host+'nots/news/media/news-and-alerts',headers=self.headers).json()
return resp

def todayPrice(self,scrip=None):
"""
Get Live Price of All The Securities in one call or specify
"""
resp = requests.get(self.host+'nots/nepse-data/today-price?&size=500',headers=self.headers).json()['content']
if scrip ==None:
return resp
return [script for script in resp if script['symbol']==scrip.upper()][0]

def markCap(self):
"""
Get Market Caps
"""
resp =requests.get(self.host+'nots/nepse-data/marcapbydate/?',headers=self.headers).json()
return resp

def getChartHistory(self,scrip,start_date=None,end_date=None):
"""
returns charts data
raises Exception if start_date or end_date != working_days (will fix it)
"""

scripID = [security for security in self.securities if security['symbol']==scrip.upper()][0]['securityId']
resp = requests.get(self.host+f'nots/market/graphdata/{scripID}',headers=self.headers).json()
if start_date:
start_date = self.dateFilter(start_date,resp)
start_index = next((index for (index, d) in enumerate(resp) if d["businessDate"] == start_date), None)
resp = resp[start_index:]
if end_date:

end_date = self.dateFilter(end_date,resp)
end_index =next((index for (index, d) in enumerate(resp) if d["businessDate"] == end_date), None)+1
if start_date and end_date:
if end_index == start_index:
end_index =-1
resp = resp[:end_index]
return resp

def createChart(self,scrip,theme='dark',start_date=None,end_date=None,close=True,high=True,low=True):

symbol = scrip.upper()
if theme.upper()=='DARK':
plt.style.use(['dark_background'])

data=self.getChartHistory(symbol,start_date,end_date)
open_price = [d['openPrice'] for d in data]
x=[d['businessDate'] for d in data]
high_data= [d['highPrice'] for d in data]
low_data = [d['lowPrice'] for d in data]
close_price= [d['closePrice'] for d in data]

plt.plot(open_price,label='Open Price')
if close:
plt.plot(close_price,label="Close Price")
if high:
plt.plot(high_data,label="High")
if low:
plt.plot(low_data,label="Low")

plt.legend(loc="upper left")

plt.title(f'{symbol} Prices As of {x[-1]}')

plt.xlabel(f"Start Date : {x[0]} | END DATE : {x[-1]}\n\nOPEN PRICE : {open_price[-1]} | ClOSE PRICE : {close_price[-1]} | High : {high_data[-1]} | Low : {low_data[-1]}")
ax=plt.gcf().autofmt_xdate()
ax = plt.gca()
ax.axes.xaxis.set_ticks([])
filename =f'{symbol}_{str(time.time())}.png'
data=plt.savefig(filename)
abspath = os.path.abspath(filename)
plt.clf()
return {'file':abspath}

def saveCSV(self,scrip,start_date=None,end_date=None,filename=None):
scripID = [security for security in self.securities if security['symbol']==scrip.upper()][0]['securityId']
resp = self.getChartHistory(scrip,start_date,end_date)
if not filename:
filename = f'{scrip.upper()}_{str(time.time())}.csv'
pd.DataFrame(resp).to_csv(filename)
return os.path.abspath(filename)





if __name__ =='__main__':
data= NEPSE()
print(data.createChart('CGH'))
22 changes: 22 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from setuptools import setup, find_packages
import codecs
from os import path
this_directory = path.abspath(path.dirname(__file__))
VERSION = '0.1.0'
DESCRIPTION = 'Python Wrapper for Newweb Nepse'
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
LONG_DESCRIPTION = f.read()

# Setting up
setup(
name="nepse",
version=VERSION,
author="FRAPPÉ (FRAPPÉ#4101)",
description=DESCRIPTION,
long_description_content_type="text/markdown",
long_description=LONG_DESCRIPTION,
packages=find_packages(),
url='https://github.com/pyFrappe/nepse',
install_requires=['requests','matplotlib','pandas'],
keywords=['python', 'nepse', 'stock', 'nepal stock', 'nepal stock prices', 'nepse pythonb']
)

0 comments on commit a6c073a

Please sign in to comment.