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 \n OPEN 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' ))
0 commit comments