Skip to content

Commit a6c073a

Browse files
committed
CSV and Nonworking Days
0 parents  commit a6c073a

File tree

10 files changed

+288
-0
lines changed

10 files changed

+288
-0
lines changed

.gitignore

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Distribution / packaging
2+
.Python
3+
build/
4+
develop-eggs/
5+
dist/
6+
downloads/
7+
eggs/
8+
.eggs/
9+
lib/
10+
lib64/
11+
parts/
12+
sdist/
13+
var/
14+
wheels/
15+
*.egg-info/
16+
.installed.cfg
17+
*.egg

README.md

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# NEPSE
2+
## _The Last Nepse Module You'll Ever Need_
3+
4+
Nepse is a realtime nepse scraper which communicates with newweb.nepalstock.com.np, to fetch and return required stats.
5+
6+
7+
## Features
8+
9+
- Get Brokers
10+
- Get Realtime Prices
11+
- Make Charts and Many More
12+
13+
14+
15+
## Installation
16+
17+
Nepse requires [python3 and pip](http://python.org/) to install and run.
18+
19+
```sh
20+
pip install nepse
21+
```
22+
23+
24+
## Plugins
25+
26+
Nepse is currently extended with the following plugins.
27+
Instructions on how to use them in your own application are linked below.
28+
29+
| Plugin | LINK |
30+
| ------ | ------ |
31+
| Matplotlib | https://matplotlib.org/|
32+
| Requests | https://pypi.org/project/requests/ |
33+
| Pandas (For Next Update) | https://pandas.pydata.org/ |
34+
35+
## Usage
36+
37+
38+
```py
39+
from nepse import NEPSE
40+
init = NEPSE()
41+
42+
#GET ALL REGISTERED BROKERS
43+
brokers = init.brokers()
44+
45+
#GET ALL NEWS & ALERTS Published By NEPSE on Newweb
46+
news= init.alerts()
47+
48+
#Check IF MARKET IS OPEN
49+
isOpen = init.isOpen() #Returns TRUE IF market is open
50+
51+
#Check live price of specific scrip or get all prices
52+
allPrices = init.todayPrice()
53+
cghPrice = init.todayPrice('CGH') #returns information for CGH
54+
55+
#CHARTS
56+
chartHistory = init.getChartHistory('CGH') #Get History Prices for CGH
57+
chartHistoryButFiltered = init.getChartHistory('CGH',start_date='2021-03-04',end_date='2021-03-07')
58+
59+
makeChart= init.createChart('CGH',theme='dark',high=False,low=False)#returns abspath of chart saved
60+
61+
csv = init.saveCSV('CGH',start_date='2021-02-07')#filename,start_date and end_date are optional
62+
63+
64+
```
65+
66+
67+
## License
68+
69+
MIT
70+

nepse/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
from nepse.stonk import NEPSE
185 Bytes
Binary file not shown.
185 Bytes
Binary file not shown.
5.37 KB
Binary file not shown.
6.78 KB
Binary file not shown.
6.72 KB
Binary file not shown.

nepse/stonk.py

Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
import requests
2+
import matplotlib.pyplot as plt
3+
import pandas as pd
4+
from datetime import datetime,timedelta
5+
import time
6+
import os
7+
8+
class NEPSE:
9+
10+
def __init__(self):
11+
self.headers= {
12+
'authority': 'newweb.nepalstock.com.np',
13+
'sec-ch-ua': '^\\^Google',
14+
'accept': 'application/json, text/plain, */*',
15+
'sec-ch-ua-mobile': '?0',
16+
'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',
17+
'sec-fetch-site': 'same-origin',
18+
'sec-fetch-mode': 'cors',
19+
'sec-fetch-dest': 'empty',
20+
'referer': 'https://newweb.nepalstock.com.np/',
21+
'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
22+
}
23+
self.host = 'https://newweb.nepalstock.com.np/api/'
24+
self.securities = requests.get(self.host+'nots/securityDailyTradeStat/58',headers=self.headers).json()
25+
pass
26+
27+
28+
def dateFilter(self,working_date,data):
29+
"""
30+
Function to return next working day , if the date provided is non-working day.
31+
32+
Returns either first or last date if the date provided is too ahead or too back.
33+
34+
"""
35+
36+
all_dates =[date['businessDate'] for date in data]
37+
if working_date in all_dates:
38+
return working_date
39+
else:
40+
i=0
41+
while 1:
42+
43+
date=datetime.strptime(working_date,'%Y-%m-%d')
44+
new_date=str(date+timedelta(days=i)).split(' ')[0]
45+
if new_date in all_dates:
46+
return new_date
47+
i+=1
48+
if i>=7:
49+
month = working_date.split('-')[1]
50+
year = working_date.split('-')[0]
51+
day=working_date.split('-')[-1]
52+
if year > all_dates[-1].split('-')[0] and month > all_dates[-1].split('-')[1]:
53+
return all_dates[-1]
54+
return all_dates[0]
55+
56+
57+
def isOpen(self):
58+
"""
59+
Returns True if the market is Open .
60+
61+
"""
62+
response = requests.get(self.host+'/nots/nepse-data/market-open', headers=self.headers).json()
63+
if response['isOpen'] !='CLOSE':
64+
return True
65+
return False
66+
67+
def brokers(self):
68+
"""
69+
70+
Returns all the registered brokers along with tms url and other information
71+
72+
"""
73+
resp = requests.get(self.host+'nots/member?&size=500',headers=self.headers).json()
74+
return resp
75+
76+
def alerts(self):
77+
"""
78+
79+
returns alerts and news published by
80+
81+
"""
82+
resp = requests.get(self.host+'nots/news/media/news-and-alerts',headers=self.headers).json()
83+
return resp
84+
85+
def todayPrice(self,scrip=None):
86+
"""
87+
88+
Get Live Price of All The Securities in one call or specify
89+
90+
"""
91+
resp = requests.get(self.host+'nots/nepse-data/today-price?&size=500',headers=self.headers).json()['content']
92+
if scrip ==None:
93+
return resp
94+
return [script for script in resp if script['symbol']==scrip.upper()][0]
95+
96+
def markCap(self):
97+
"""
98+
99+
Get Market Caps
100+
101+
"""
102+
resp =requests.get(self.host+'nots/nepse-data/marcapbydate/?',headers=self.headers).json()
103+
return resp
104+
105+
def getChartHistory(self,scrip,start_date=None,end_date=None):
106+
"""
107+
108+
returns charts data
109+
raises Exception if start_date or end_date != working_days (will fix it)
110+
111+
"""
112+
113+
scripID = [security for security in self.securities if security['symbol']==scrip.upper()][0]['securityId']
114+
resp = requests.get(self.host+f'nots/market/graphdata/{scripID}',headers=self.headers).json()
115+
if start_date:
116+
start_date = self.dateFilter(start_date,resp)
117+
start_index = next((index for (index, d) in enumerate(resp) if d["businessDate"] == start_date), None)
118+
resp = resp[start_index:]
119+
if end_date:
120+
121+
end_date = self.dateFilter(end_date,resp)
122+
end_index =next((index for (index, d) in enumerate(resp) if d["businessDate"] == end_date), None)+1
123+
if start_date and end_date:
124+
if end_index == start_index:
125+
end_index =-1
126+
resp = resp[:end_index]
127+
return resp
128+
129+
def createChart(self,scrip,theme='dark',start_date=None,end_date=None,close=True,high=True,low=True):
130+
131+
symbol = scrip.upper()
132+
if theme.upper()=='DARK':
133+
plt.style.use(['dark_background'])
134+
135+
data=self.getChartHistory(symbol,start_date,end_date)
136+
open_price = [d['openPrice'] for d in data]
137+
x=[d['businessDate'] for d in data]
138+
high_data= [d['highPrice'] for d in data]
139+
low_data = [d['lowPrice'] for d in data]
140+
close_price= [d['closePrice'] for d in data]
141+
142+
plt.plot(open_price,label='Open Price')
143+
if close:
144+
plt.plot(close_price,label="Close Price")
145+
if high:
146+
plt.plot(high_data,label="High")
147+
if low:
148+
plt.plot(low_data,label="Low")
149+
150+
plt.legend(loc="upper left")
151+
152+
plt.title(f'{symbol} Prices As of {x[-1]}')
153+
154+
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]}")
155+
ax=plt.gcf().autofmt_xdate()
156+
ax = plt.gca()
157+
ax.axes.xaxis.set_ticks([])
158+
filename =f'{symbol}_{str(time.time())}.png'
159+
data=plt.savefig(filename)
160+
abspath = os.path.abspath(filename)
161+
plt.clf()
162+
return {'file':abspath}
163+
164+
def saveCSV(self,scrip,start_date=None,end_date=None,filename=None):
165+
scripID = [security for security in self.securities if security['symbol']==scrip.upper()][0]['securityId']
166+
resp = self.getChartHistory(scrip,start_date,end_date)
167+
if not filename:
168+
filename = f'{scrip.upper()}_{str(time.time())}.csv'
169+
pd.DataFrame(resp).to_csv(filename)
170+
return os.path.abspath(filename)
171+
172+
173+
174+
175+
176+
if __name__ =='__main__':
177+
data= NEPSE()
178+
print(data.createChart('CGH'))

setup.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
from setuptools import setup, find_packages
2+
import codecs
3+
from os import path
4+
this_directory = path.abspath(path.dirname(__file__))
5+
VERSION = '0.1.0'
6+
DESCRIPTION = 'Python Wrapper for Newweb Nepse'
7+
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
8+
LONG_DESCRIPTION = f.read()
9+
10+
# Setting up
11+
setup(
12+
name="nepse",
13+
version=VERSION,
14+
author="FRAPPÉ (FRAPPÉ#4101)",
15+
description=DESCRIPTION,
16+
long_description_content_type="text/markdown",
17+
long_description=LONG_DESCRIPTION,
18+
packages=find_packages(),
19+
url='https://github.com/pyFrappe/nepse',
20+
install_requires=['requests','matplotlib','pandas'],
21+
keywords=['python', 'nepse', 'stock', 'nepal stock', 'nepal stock prices', 'nepse pythonb']
22+
)

0 commit comments

Comments
 (0)