def index(): nse = Nse() top_gainers = nse.get_top_gainers() top_losers = nse.get_top_losers() return render_template('marketcards.html', gainers=top_gainers, losers=top_losers)
def nse_stock(self): nse = Nse() print("TOP GAINERS OF YESTERDAY") print(nse.get_top_gainers()) print( '-------------------------------------------------------------------------------------------------------' ) print("TOP LOSERS OF YESTERDAY") print(nse.get_top_losers())
class Gainers(object): def __init__(self): self.nse = Nse() self.data = self.nse.get_top_gainers(as_json=True) @property def top_gainers(self): data = json.loads(self.data) df = pd.DataFrame(data) df = df[df['openPrice'] < 300] return df[['symbol', 'openPrice', 'highPrice', 'lowPrice', 'netPrice']]
def getGainValue(): today = date.today() nse= Nse() top_gainers = pd.DataFrame(nse.get_top_gainers()) #print(top_gainers) filenames= {} filenames['TG'] = 'Files/TopGainers'+str(today)+'.csv' top_gainers.to_csv(filenames['TG']) print(filenames) return top_gainers
def Stock_Gainers_Losers(My_Selection): global Selection Selection = My_Selection nse = Nse() if Selection == 'Gain': top = nse.get_top_gainers() else: top = nse.get_top_losers() global Top_Stock Top_Stock = top app_Gainers_Losers = MyApp_Gainers_Losers(0) app_Gainers_Losers.MainLoop()
class Parser(): nse = None log_infix = 'Parser::' default_query_list = [ 'symbol', 'companyName', 'dayHigh', 'basePrice', 'dayLow', 'averagePrice', 'high52', 'low52' ] def __init__(self): self.nse = Nse() self.log_infix + '__init__ ' logging.info('%s %s', (self.log_infix, self.nse)) def quote_by_stock_name(self, name, query_list=[]): self.log_infix + 'quote_by_stock_name ' if (not name): message = 'Name should be present' logging.error(self.log_infix + message) raise NameError(message) if (not self.nse): message = 'NSE Object Failure' logging.error(self.log_infix + message) raise ValueError(message) print(f'nse value is {self.nse} and name is {name}') query = self.nse.get_quote(name) if (len(query_list) > 0): queries = query_list else: queries = self.default_query_list nse_obj = nse_object(query).retrieve_info(queries) return nse_obj def get_top_gainers(self): self.log_infix + 'get_top_gainers ' if (not self.nse): message = 'NSE Object Failure' logging.error(self.log_infix + message) raise ValueError(message) query = self.nse.get_top_gainers() nse_obj = nse_object(query).retrieve_info([]) return nse_obj
class Command(BaseCommand): def __init__(self): self.trending_company_repo = TrendingCompanyRepo() self.company_repo = CompanyRepo() self.nse = Nse() def run(self): gainers = self.nse.get_top_gainers()[:5] losers = self.nse.get_top_losers()[:5] print gainers, losers return g_comapnies = [ self.company_repo.get_or_create(code=g['symbol']) for g in gainers ] l_comapnies = [ self.company_repo.get_or_create(code=l['symbol']) for l in losers ] trendings = g_comapnies.extends(l_comapnies) date = helper.today() try: self.trending_company_repo.create(date=date, trendings=trendings) except Exception as e: print "error", e print "Done"
def detail(request, product_id): nse = Nse() top_gainers = nse.get_top_gainers() top_losers = nse.get_top_losers() response = requests.get(bseurl) bsedetail = response.json() response = requests.get(nseurl) nsedetail = response.json() response = requests.get(usdinrurl) usdinrdetail = response.json() response = requests.get(goldurl) golddetail = response.json() productcode = get_object_or_404(Product, pk=product_id) url = 'https://www.quandl.com/api/v3/datasets/AMFI/' + str( productcode.stockid) + '.json?api_key=a6QtRRy_axhp9mTMRvyC' url2 = 'https://www.quandl.com/api/v3/datasets/BSE/SENSEX.json?api_key=a6QtRRy_axhp9mTMRvyC' print(url) response = requests.get(url) stockdetail = response.json() return render( request, 'products/detail.html', { 'stockdetail': stockdetail['dataset'], 'topgainers': top_gainers_nse, 'toplosers': top_losers_nse, 'bsedetail': bsedetail, 'nifty': nsedetail, 'usdinrdetail': usdinrdetail, 'golddetail': golddetail, 'topgainersnse': top_gainers_nse, 'toplosersnse': top_losers_nse, 'topgainersbse': top_gainers_bse, 'toplosersbse': top_losers_bse, })
class TestCoreAPIs(unittest.TestCase): def setUp(self): self.nse = Nse() def test_string_representation(self): self.assertEqual(str(self.nse) , "Driver Class for National Stock Exchange (NSE)") def test_instantiate_abs_class(self): class Exchange(AbstractBaseExchange): pass with self.assertRaises(TypeError): exc = Exchange() def test_nse_headers(self): ret = self.nse.nse_headers() self.assertIsInstance(ret, dict) def test_nse_opener(self): ''' should not raise any exception ''' opener = self.nse.nse_opener() def test_build_url_for_quote(self): test_code = 'infy' url = self.nse.build_url_for_quote(test_code) # 'test_code' should be present in the url self.assertIsNotNone(re.search(test_code, url)) def test_negative_build_url_for_quote(self): negative_codes = [1, None] with self.assertRaises(Exception): for test_code in negative_codes: url = self.nse.build_url_for_quote(test_code) def test_response_cleaner(self): test_dict = { 'a': '10', 'b': '10.0', 'c': '1,000.10', 'd': 'vsjha18', 'e': 10, 'f': 10.0, 'g': 1000.10, 'h': True, 'i': None, 'j': u'10', 'k': u'10.0', 'l': u'1,000.10' } expected_dict = { 'a': 10, 'b': 10.0, 'c': 1000.10, 'd': 'vsjha18', 'e': 10, 'f': 10.0, 'g': 1000.10, 'h': True, 'i': None, 'j': 10, 'k': 10.0, 'l': 1000.10 } ret_dict = self.nse.clean_server_response(test_dict) self.assertDictEqual(ret_dict, expected_dict) def test_get_stock_codes(self): sc = self.nse.get_stock_codes() self.assertIsNotNone(sc) self.assertIsInstance(sc, dict) # test the json format return sc_json = self.nse.get_stock_codes(as_json=True) self.assertIsInstance(sc_json, str) # reconstruct the dict from json and compare self.assertItemsEqual(sc, json.loads(sc_json)) # TODO: use mock and create one test where response contains a blank line # TODO: use mock and create one test where response doesnt contain a csv # TODO: use mock and create one test where return is null # TODO: test the cache feature def test_negative_get_quote(self): wrong_code = 'inf' self.assertIsNone(self.nse.get_quote(wrong_code)) def test_get_quote(self): code = 'infy' resp = self.nse.get_quote(code) self.assertIsInstance(resp, dict) # test json response json_resp = self.nse.get_quote(code, as_json=True) self.assertIsInstance(json_resp, str) # reconstruct the original dict from json # this test may raise false alarms in case the # the price changed in that very moment. self.assertDictEqual(resp, json.loads(json_resp)) def test_is_valid_code(self): code = 'infy' self.assertTrue(self.nse.is_valid_code(code)) def test_negative_is_valid_code(self): wrong_code = 'in' self.assertFalse(self.nse.is_valid_code(wrong_code)) def test_get_top_gainers(self): res = self.nse.get_top_gainers() self.assertIsInstance(res, list) # test json response res = self.nse.get_top_gainers(as_json=True) self.assertIsInstance(res, str) def test_get_top_losers(self): res = self.nse.get_top_losers() self.assertIsInstance(res, list) def test_render_response(self): d = {'fname':'vivek', 'lname':'jha'} resp_dict = self.nse.render_response(d) resp_json = self.nse.render_response(d, as_json=True) # in case of dict, response should be a python dict self.assertIsInstance(resp_dict, dict) # in case of json, response should be a json string self.assertIsInstance(resp_json, str) # and on reconstruction it should become same as original dict self.assertDictEqual(d, json.loads(resp_json)) def test_advances_declines(self): resp = self.nse.get_advances_declines() # it should be a list of dictionaries self.assertIsInstance(resp, list) # get the json version resp_json = self.nse.get_advances_declines(as_json=True) self.assertIsInstance(resp_json, str) # load the json response and it should have same number of # elements as in case of first response self.assertEqual(len(resp), len(json.loads(resp_json))) def test_is_valid_index(self): code = 'CNX NIFTY' self.assertTrue(self.nse.is_valid_index(code)) # test with invalid string code = 'some junk stuff' self.assertFalse(self.nse.is_valid_index(code)) # test with lower case code = 'cnx nifty' self.assertTrue(self.nse.is_valid_index(code)) def test_get_index_quote(self): code = 'CNX NIFTY' self.assertIsInstance(self.nse.get_index_quote(code), dict) # with json response self.assertIsInstance(self.nse.get_index_quote(code, as_json=True), str) # with wrong code code = 'wrong code' self.assertIsNone(self.nse.get_index_quote(code)) # with lower case code code = 'cnx nifty' self.assertIsInstance(self.nse.get_index_quote(code), dict) def test_get_index_list(self): index_list = self.nse.get_index_list() index_list_json = self.nse.get_index_list(as_json=True) self.assertIsInstance(index_list, list) # test json response type self.assertIsInstance(index_list_json, str) # reconstruct list from json and match self.assertListEqual(index_list, json.loads(index_list_json))
def webhook(): nse = Nse() with open('symbols.json') as json_file: symbol_data = json.load(json_file) with open('inv_symbols.json') as json_file: inv_symbol_data = json.load(json_file) newsapi = NewsApiClient(api_key='cc0446450bcc4e46a91abd02e33d5f85') req = request.get_json(silent=True, force=True) query_result = req.get('queryResult') if query_result.get('action') == 'get_stock_price': # query_result = req.get('queryResult') price_type = query_result.get('parameters').get('price_type') company_name = query_result.get('parameters').get('company_name') date_time = query_result.get('parameters').get('date-time') if isinstance(date_time, str): s = date_time.split("T")[0] unix_time = int( time.mktime( datetime.datetime.strptime(s, "%Y-%m-%d").timetuple())) else: s = date_time['date_time'].split("T")[0] unix_time = int( time.mktime( datetime.datetime.strptime(s, "%Y-%m-%d").timetuple())) start_date = unix_time end_date = unix_time + 86399 try: company_symbol = symbol_data[company_name] except: return { "fulfillmentText": "Sorry! You need to enter a NSE belonging company.", "displayText": '25', "source": "webhookdata" } q = nse.get_quote(company_symbol) prices = { "opening": q['open'], "closing": q['lastPrice'], "high": q['dayHigh'], "low": q['dayLow'] } human_readable_date = datetime.datetime.utcfromtimestamp( unix_time).strftime("%d %B, %Y") op_string = "The {} price of {} on {} was Rs.{}.".format( price_type, company_name, human_readable_date, prices[price_type]) return { "fulfillmentText": op_string, "displayText": '25', "source": "webhookdata" } elif query_result.get('action') == 'get_gainer': gainer_type = query_result.get('parameters').get('gainer_type') if query_result.get('parameters').get('number') == '': number = 1 else: number = int(query_result.get('parameters').get('number')) top_gainers = nse.get_top_gainers() top_losers = nse.get_top_losers() if gainer_type == 'gainer': if number == 1: c_name = inv_symbol_data[top_gainers[0].get('symbol')] op_string = "The top gainer for the last trading session is {}.".format( c_name) else: company_list = [] for i in range(number - 1): company_list.append( inv_symbol_data[top_gainers[i].get('symbol')]) company_string = ", ".join(company_list) company_string += " and {}".format( inv_symbol_data[top_gainers[number - 1].get('symbol')]) op_string = "The top {} {}s are {}.".format( number, gainer_type, company_string) else: if number == 1: c_name = inv_symbol_data[top_losers[0].get('symbol')] op_string = "The top loser for the last trading session is {}.".format( c_name) else: company_list = [] for i in range(number - 1): company_list.append( inv_symbol_data[top_losers[i].get('symbol')]) company_string = ", ".join(company_list) company_string += " and {}".format( inv_symbol_data[top_losers[number - 1].get('symbol')]) op_string = "The top {} {}s are {}.".format( number, gainer_type, company_string) return { "fulfillmentText": op_string, "displayText": '25', "source": "webhookdata" } elif query_result.get('action') == 'get_news': company_name = query_result.get('parameters').get('company_name') all_articles = newsapi.get_everything( qintitle=company_name, sources='bbc-news,the-verge,the-times-of-india', language='en', sort_by='relevancy') articles = all_articles.get('articles') if len(articles) == 0: return { "fulfillmentText": "Sorry! Could not find any relevant news.", "displayText": '25', "source": "webhookdata" } article = articles[random.randint(0, len(articles) - 1)] # pprint(article) title = article.get('title') url = article.get('url') url_img = article.get('urlToImage') subtitle = article.get('description') response = [{ "card": { "title": title, "subtitle": subtitle, "imageUri": url_img, "buttons": [{ "text": "Read Full Story", "postback": url }, { "text": "Get more news", "postback": "Get more news for {}".format(company_name) }] }, "platform": "FACEBOOK" }] return jsonify({"fulfillmentMessages": response}) elif query_result.get('action') == 'get_index_quote': index_code = query_result.get('parameters').get('index_codes') if index_code == "": op_string = 'Try again using a valid Index code.' else: index_quote = nse.get_index_quote(index_code).get('lastPrice') op_string = "The last updated price of {} is Rs.{}.".format( index_code.upper(), index_quote) return { "fulfillmentText": op_string, "displayText": '25', "source": "webhookdata" } elif query_result.get('action') == 'get_advances': trade_index = query_result.get('parameters').get('index_codes') advance_type = query_result.get('parameters').get('advance_type') print(trade_index) if trade_index == '': op_string = 'Try again using a valid Index code.' else: adv_dec = nse.get_advances_declines() flag = 0 for i in adv_dec: if i.get('indice') == trade_index: advances = i.get('advances') declines = i.get('declines') flag = 1 break if flag == 0: op_string = "No data of advances/declines for this index was found." else: if advance_type == 'advance': op_string = "The advances of {} are {}.".format( trade_index, advances) else: op_string = "The declines of {} are {}.".format( trade_index, declines) print(op_string) return { "fulfillmentText": op_string, "displayText": '25', "source": "webhookdata" }
class TestCoreAPIs(unittest.TestCase): def setUp(self): self.nse = Nse() def test_string_representation(self): self.assertEqual(str(self.nse), "Driver Class for National Stock Exchange (NSE)") def test_instantiate_abs_class(self): class Exchange(AbstractBaseExchange): pass with self.assertRaises(TypeError): exc = Exchange() def test_nse_headers(self): ret = self.nse.nse_headers() self.assertIsInstance(ret, dict) def test_nse_opener(self): ''' should not raise any exception ''' opener = self.nse.nse_opener() def test_build_url_for_quote(self): test_code = 'infy' url = self.nse.build_url_for_quote(test_code) # 'test_code' should be present in the url self.assertIsNotNone(re.search(test_code, url)) def test_negative_build_url_for_quote(self): negative_codes = [1, None] with self.assertRaises(Exception): for test_code in negative_codes: url = self.nse.build_url_for_quote(test_code) def test_response_cleaner(self): test_dict = { 'a': '10', 'b': '10.0', 'c': '1,000.10', 'd': 'vsjha18', 'e': 10, 'f': 10.0, 'g': 1000.10, 'h': True, 'i': None, 'j': u'10', 'k': u'10.0', 'l': u'1,000.10' } expected_dict = { 'a': 10, 'b': 10.0, 'c': 1000.10, 'd': 'vsjha18', 'e': 10, 'f': 10.0, 'g': 1000.10, 'h': True, 'i': None, 'j': 10, 'k': 10.0, 'l': 1000.10 } ret_dict = self.nse.clean_server_response(test_dict) self.assertDictEqual(ret_dict, expected_dict) def test_get_stock_codes(self): sc = self.nse.get_stock_codes() self.assertIsNotNone(sc) self.assertIsInstance(sc, dict) # test the json format return sc_json = self.nse.get_stock_codes(as_json=True) self.assertIsInstance(sc_json, str) # reconstruct the dict from json and compare six.assertCountEqual(self, sc, json.loads(sc_json)) # TODO: use mock and create one test where response contains a blank line # TODO: use mock and create one test where response doesnt contain a csv # TODO: use mock and create one test where return is null # TODO: test the cache feature def test_negative_get_quote(self): wrong_code = 'inf' self.assertIsNone(self.nse.get_quote(wrong_code)) def test_get_quote(self): code = 'infy' resp = self.nse.get_quote(code) self.assertIsInstance(resp, dict) # test json response json_resp = self.nse.get_quote(code, as_json=True) self.assertIsInstance(json_resp, str) # reconstruct the original dict from json # this test may raise false alarms in case the # the price changed in that very moment. self.assertDictEqual(resp, json.loads(json_resp)) def test_is_valid_code(self): code = 'infy' self.assertTrue(self.nse.is_valid_code(code)) def test_negative_is_valid_code(self): wrong_code = 'in' self.assertFalse(self.nse.is_valid_code(wrong_code)) def test_get_top_gainers(self): res = self.nse.get_top_gainers() self.assertIsInstance(res, list) # test json response res = self.nse.get_top_gainers(as_json=True) self.assertIsInstance(res, str) def test_get_top_losers(self): res = self.nse.get_top_losers() self.assertIsInstance(res, list) def test_render_response(self): d = {'fname':'vivek', 'lname':'jha'} resp_dict = self.nse.render_response(d) resp_json = self.nse.render_response(d, as_json=True) # in case of dict, response should be a python dict self.assertIsInstance(resp_dict, dict) # in case of json, response should be a json string self.assertIsInstance(resp_json, str) # and on reconstruction it should become same as original dict self.assertDictEqual(d, json.loads(resp_json)) def test_advances_declines(self): resp = self.nse.get_advances_declines() # it should be a list of dictionaries self.assertIsInstance(resp, list) # get the json version resp_json = self.nse.get_advances_declines(as_json=True) self.assertIsInstance(resp_json, str) # load the json response and it should have same number of # elements as in case of first response self.assertEqual(len(resp), len(json.loads(resp_json))) def test_is_valid_index(self): code = 'NIFTY BANK' self.assertTrue(self.nse.is_valid_index(code)) # test with invalid string code = 'some junk stuff' self.assertFalse(self.nse.is_valid_index(code)) # test with lower case code = 'nifty bank' self.assertTrue(self.nse.is_valid_index(code)) def test_get_index_quote(self): code = 'NIFTY BANK' self.assertIsInstance(self.nse.get_index_quote(code), dict) # with json response self.assertIsInstance(self.nse.get_index_quote(code, as_json=True), str) # with wrong code code = 'wrong code' self.assertIsNone(self.nse.get_index_quote(code)) # with lower case code code = 'nifty bank' self.assertIsInstance(self.nse.get_index_quote(code), dict) def test_get_index_list(self): index_list = self.nse.get_index_list() index_list_json = self.nse.get_index_list(as_json=True) self.assertIsInstance(index_list, list) # test json response type self.assertIsInstance(index_list_json, str) # reconstruct list from json and match self.assertListEqual(index_list, json.loads(index_list_json)) def test_jsadptor(self): buffer = 'abc:true, def:false, ghi:NaN, jkl:none' expected_buffer = 'abc:True, def:False, ghi:"NaN", jkl:None' ret = js_adaptor(buffer) self.assertEqual(ret, expected_buffer) def test_byte_adaptor(self): if six.PY2: from StringIO import StringIO buffer = 'nsetools' fbuffer = StringIO(buffer) else: from io import BytesIO buffer = b'nsetools' fbuffer = BytesIO(buffer) ret_file_buffer = byte_adaptor(fbuffer) self.assertIsInstance(ret_file_buffer, six.StringIO) def test_nse_lot_sizes(self): data = self.nse.get_fno_lot_sizes() self.assertIsInstance(data, dict) def test_6th_Dec_1994(self): data = self.nse.download_bhavcopy('1994-12-06') self.assertIsInstance(self, data, bytes) def test_top_fno_gainers_losers(self): fno_gainer = self.nse.get_top_fno_gainers() self.assertIsInstance(fno_gainer, list) fno_gainer_json = self.nse.get_top_fno_gainers(as_json=True) self.assertIsInstance(fno_gainer_json, str) fno_loser = self.nse.get_top_fno_losers() self.assertIsInstance(fno_loser, list) fno_loser_json = self.nse.get_top_fno_losers(as_json=True) self.assertIsInstance(fno_loser_json, str) def test_statistics(self): active = self.nse.get_active_monthly() self.assertIsInstance(active, list) active_json = self.nse.get_active_monthly(as_json=True) self.assertIsInstance(active_json, str) yr_high = self.nse.get_year_high() self.assertIsInstance(yr_high, list) yr_high_json = self.nse.get_year_high(as_json=True) self.assertIsInstance(yr_high_json, str) yr_low = self.nse.get_year_low() self.assertIsInstance(yr_low, list) yr_low_json = self.nse.get_year_low(as_json=True) self.assertIsInstance(yr_low_json, str) preopen = self.nse.get_preopen_nifty() self.assertIsInstance(preopen, list) preopen_json = self.nse.get_preopen_nifty(as_json=True) self.assertIsInstance(preopen_json, str) preopen_nb = self.nse.get_preopen_niftybank() self.assertIsInstance(preopen_nb, list) preopen_nb_json = self.nse.get_preopen_niftybank(as_json=True) self.assertIsInstance(preopen_nb_json, str) preopen_fno = self.nse.get_preopen_fno() self.assertIsInstance(preopen_fno, list) preopen_fno_json = self.nse.get_preopen_fno(as_json=True) self.assertIsInstance(preopen_fno_json, str)
parser.add_argument("-l", "--loss", action='store_true', help="commands") #parser.add_argument("-p", "--portfolio", nargs='?', const="f", help="get_price.py -p [xl] ; t - to create xls") parser.add_argument("-p", "--portfolio", type=str, help="get_price.py -p <portfolio name>") parser.add_argument("-q", "--quote", type=str, help="get_price.py -q <watchlist name>") if len(sys.argv) == 1: parser.print_help(sys.stderr) sys.exit(1) args = parser.parse_args() if args.gain: show_top(nse.get_top_gainers(), 'Gainers') if args.loss: show_top(nse.get_top_losers(), 'Losers') if args.portfolio: fname = args.portfolio show_portfolio(fname) #else: # show_portfolio() if args.quote: watchlist = args.quote show_quote(watchlist)
def fetch_gainers(): nse = Nse() return nse.get_top_gainers(as_json=True)
def append_list_as_row(file_name, list_of_elem): # Open file in append mode with open(file_name, 'a+', newline='') as write_obj: # Create a writer object from csv module csv_writer = writer(write_obj) # Add contents of list as last row in the csv file csv_writer.writerow(list_of_elem) nse= Nse() #this list just stores names of the required stocks so that #you can use this directly into your code and use accordingly stocks_list = [] #top gainers top_gainers = nse.get_top_gainers() #remove comment of the next line to see all fields available #pprint(top_gainers[0]) #insert column titles row=['Stock name','Open price','High price','Low price','Previous price','Volume','Ltp'] #inserts the columns names into the csv file append_list_as_row('topGainers.csv',row) #change value of range to receive your required numbers of stocks max-10 for i in range(5): stock_name=top_gainers[i]['symbol'] open_price=top_gainers[i]['openPrice']
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from rest_framework.views import APIView from rest_framework.response import Response from nsetools import Nse from pprint import pprint # just for neatness of display from datetime import datetime, timedelta import pandas as pd import io from bsedata.bse import BSE import requests from django import template defaultfundprice = 0 search_term = '' nse = Nse() top_gainers_nse = nse.get_top_gainers() top_losers_nse = nse.get_top_losers() bse = BSE() top_gainers_bse = bse.topGainers() top_losers_bse = bse.topLosers() ##moneycontrol appfeeds bseurl = 'http://appfeeds.moneycontrol.com/jsonapi/market/indices&ind_id=4' nseurl = 'http://appfeeds.moneycontrol.com/jsonapi/market/indices&ind_id=9' usdinrurl = 'https://priceapi.moneycontrol.com/pricefeed/notapplicable/currencyspot/%24%24%3BUSDINR' goldurl = 'https://priceapi.moneycontrol.com/pricefeed/mcx/commodityfuture/GOLD?expiry=05FEB2020' # Create your views here. def getPageData(request, allFundList):
cred = credentials.Certificate("./ServiceAccountKey.json") app = firebase_admin.initialize_app(cred) # Instantiate Firestore class db = firestore.client() # Instantiate batch class to update data in single batch batch = db.batch() # Set the data structure doc_ref_top_gainers = db.collection(u'nse').document(u'top_gainers') doc_ref_top_losers = db.collection(u'nse').document(u'top_losers') doc_ref_advances_declines = db.collection(u'nse').document( u'advances_declines') # write to database while True: if (current_time[0][:3].lower() in ['mon', 'tue', 'wed', 'thu', 'fri']) \ and \ (9 < int(current_time[0][:2]) < 17): batch.update(doc_ref_top_gainers, {u'top_gainers': nse.get_top_gainers()}) batch.update(doc_ref_top_losers, {u'top_losers': nse.get_top_losers()}) batch.update(doc_ref_advances_declines, {u'advances_declines': nse.get_advances_declines()}) # commit batch batch.commit() print(nse) sleep(600) current_time = ctime(time()).split()
from pprint import pprint from nsetools import Nse nse = Nse() top_gainers = nse.get_top_gainers() pprint(top_gainers) top_losers = nse.get_top_losers() pprint(top_losers)
from nsetools import Nse from flask import Flask import pprint app = Flask(__name__) gainers={} nse = Nse() companies=nse.get_top_gainers() @app.route('/today') def gainer(): for item in companies: gainers[item['symbol']]=item['netPrice'] pprint.pprint(gainers) return gainers if __name__ == '__main__': app.run()
def welcome(): nse = Nse() top_gainers = nse.get_top_gainers() top_0 = top_gainers[0] top_0_symbol = top_0['symbol'] top_0_price = top_0['previousPrice'] top_1 = top_gainers[1] top_1_symbol = top_1['symbol'] top_1_price = top_1['previousPrice'] top_2 = top_gainers[2] top_2_symbol = top_2['symbol'] top_2_price = top_2['previousPrice'] top_3 = top_gainers[3] top_3_symbol = top_3['symbol'] top_3_price = top_3['previousPrice'] top_4 = top_gainers[4] top_4_symbol = top_4['symbol'] top_4_price = top_4['previousPrice'] top_losers = nse.get_top_losers() top_5 = top_losers[0] top_5_symbol = top_5['symbol'] top_5_price = top_5['previousPrice'] top_6 = top_losers[1] top_6_symbol = top_6['symbol'] top_6_price = top_6['previousPrice'] top_7 = top_losers[2] top_7_symbol = top_7['symbol'] top_7_price = top_7['previousPrice'] top_8 = top_losers[3] top_8_symbol = top_8['symbol'] top_8_price = top_8['previousPrice'] top_9 = top_losers[4] top_9_symbol = top_9['symbol'] top_9_price = top_9['previousPrice'] infy = nse.get_quote('infy') infy1 = infy['lastPrice'] infyclosing = infy['previousClose'] diffInfy = infy1 - infyclosing if(diffInfy > 0): icolor = 'green' iarrow = 'up' else: icolor = 'red' iarrow = 'bottom' infyans = manipulate(infy1,infyclosing) tcs = nse.get_quote('tcs') tcs1 = tcs['lastPrice'] tcsclosing = tcs['previousClose'] diffTcs = tcs1 - tcsclosing if(diffTcs > 0): tcolor = 'green' tarrow = 'up' else: tcolor = 'red' tarrow = 'bottom' tcsans = manipulate(tcs1,tcsclosing) itc = nse.get_quote('itc') itc1 = itc['lastPrice'] itcclosing = itc['previousClose'] diffItc = itc1 - itcclosing if(diffItc > 0): itccolor = 'green' itcarrow = 'up' else: itccolor = 'red' itcarrow = 'bottom' itcans = manipulate(itc1,itcclosing) ioc = nse.get_quote('ioc') ioc1 = ioc['lastPrice'] iocclosing = ioc['previousClose'] diffioc = ioc1 - iocclosing if(diffioc > 0): iocolor = 'green' ioarrow = 'up' else: iocolor = 'red' ioarrow = 'bottom' iocans = manipulate(ioc1,iocclosing) return render_template('main.html',infy1=infy1,infy2=infyans, tcs1=tcs1,tcs2=tcsans, itc1=itc1,itc2 = itcans, ioc1=ioc1,ioc2 = iocans, symbol0 = top_0_symbol, price0=top_0_price, symbol1=top_1_symbol, price1=top_1_price, symbol2=top_2_symbol, price2=top_2_price, symbol3=top_3_symbol, price3=top_3_price, symbol4=top_4_symbol, price4=top_4_price, symbol5=top_5_symbol, price5=top_5_price, symbol6=top_6_symbol, price6=top_6_price, symbol7=top_7_symbol, price7=top_7_price, symbol8=top_8_symbol, price8=top_8_price, symbol9=top_9_symbol, price9=top_9_price,icolor=icolor,tcolor=tcolor,itcarrow=itcarrow,itccolor=itccolor,iocolor=iocolor, ioarrow=ioarrow)
class TestCoreAPIs(unittest.TestCase): def setUp(self): self.nse = Nse() def test_string_representation(self): self.assertEqual(str(self.nse) , "Driver Class for National Stock Exchange (NSE)") def test_instantiate_abs_class(self): class Exchange(AbstractBaseExchange): pass with self.assertRaises(TypeError): exc = Exchange() def test_nse_headers(self): ret = self.nse.nse_headers() self.assertIsInstance(ret, dict) def test_nse_opener(self): ''' should not raise any exception ''' opener = self.nse.nse_opener() def test_build_url_for_quote(self): test_code = 'infy' url = self.nse.build_url_for_quote(test_code) # 'test_code' should be present in the url self.assertIsNotNone(re.search(test_code, url)) def test_negative_build_url_for_quote(self): negative_codes = [1, None] with self.assertRaises(Exception): for test_code in negative_codes: url = self.nse.build_url_for_quote(test_code) def test_response_cleaner(self): test_dict = { 'a': '10', 'b': '10.0', 'c': '1,000.10', 'd': 'vsjha18', 'e': 10, 'f': 10.0, 'g': 1000.10, 'h': True, 'i': None, 'j': u'10', 'k': u'10.0', 'l': u'1,000.10' } expected_dict = { 'a': 10, 'b': 10.0, 'c': 1000.10, 'd': 'vsjha18', 'e': 10, 'f': 10.0, 'g': 1000.10, 'h': True, 'i': None, 'j': 10, 'k': 10.0, 'l': 1000.10 } ret_dict = self.nse.clean_server_response(test_dict) self.assertDictEqual(ret_dict, expected_dict) def test_get_stock_codes(self): sc = self.nse.get_stock_codes() self.assertIsNotNone(sc) self.assertIsInstance(sc, dict) # test the json format return sc_json = self.nse.get_stock_codes(as_json=True) self.assertIsInstance(sc_json, str) # reconstruct the dict from json and compare six.assertCountEqual(self, sc, json.loads(sc_json)) # TODO: use mock and create one test where response contains a blank line # TODO: use mock and create one test where response doesnt contain a csv # TODO: use mock and create one test where return is null # TODO: test the cache feature def test_negative_get_quote(self): wrong_code = 'inf' self.assertIsNone(self.nse.get_quote(wrong_code)) def test_get_quote(self): code = 'infy' resp = self.nse.get_quote(code) self.assertIsInstance(resp, dict) # test json response json_resp = self.nse.get_quote(code, as_json=True) self.assertIsInstance(json_resp, str) # reconstruct the original dict from json # this test may raise false alarms in case the # the price changed in that very moment. self.assertDictEqual(resp, json.loads(json_resp)) def test_is_valid_code(self): code = 'infy' self.assertTrue(self.nse.is_valid_code(code)) def test_negative_is_valid_code(self): wrong_code = 'in' self.assertFalse(self.nse.is_valid_code(wrong_code)) def test_get_top_gainers(self): res = self.nse.get_top_gainers() self.assertIsInstance(res, list) # test json response res = self.nse.get_top_gainers(as_json=True) self.assertIsInstance(res, str) def test_get_top_losers(self): res = self.nse.get_top_losers() self.assertIsInstance(res, list) def test_render_response(self): d = {'fname':'vivek', 'lname':'jha'} resp_dict = self.nse.render_response(d) resp_json = self.nse.render_response(d, as_json=True) # in case of dict, response should be a python dict self.assertIsInstance(resp_dict, dict) # in case of json, response should be a json string self.assertIsInstance(resp_json, str) # and on reconstruction it should become same as original dict self.assertDictEqual(d, json.loads(resp_json)) def test_advances_declines(self): resp = self.nse.get_advances_declines() # it should be a list of dictionaries self.assertIsInstance(resp, list) # get the json version resp_json = self.nse.get_advances_declines(as_json=True) self.assertIsInstance(resp_json, str) # load the json response and it should have same number of # elements as in case of first response self.assertEqual(len(resp), len(json.loads(resp_json))) def test_is_valid_index(self): code = 'CNX NIFTY' self.assertTrue(self.nse.is_valid_index(code)) # test with invalid string code = 'some junk stuff' self.assertFalse(self.nse.is_valid_index(code)) # test with lower case code = 'cnx nifty' self.assertTrue(self.nse.is_valid_index(code)) def test_get_index_quote(self): code = 'CNX NIFTY' self.assertIsInstance(self.nse.get_index_quote(code), dict) # with json response self.assertIsInstance(self.nse.get_index_quote(code, as_json=True), str) # with wrong code code = 'wrong code' self.assertIsNone(self.nse.get_index_quote(code)) # with lower case code code = 'cnx nifty' self.assertIsInstance(self.nse.get_index_quote(code), dict) def test_get_index_list(self): index_list = self.nse.get_index_list() index_list_json = self.nse.get_index_list(as_json=True) self.assertIsInstance(index_list, list) # test json response type self.assertIsInstance(index_list_json, str) # reconstruct list from json and match self.assertListEqual(index_list, json.loads(index_list_json)) def test_jsadptor(self): buffer = 'abc:true, def:false, ghi:NaN, jkl:none' expected_buffer = 'abc:True, def:False, ghi:"NaN", jkl:None' ret = js_adaptor(buffer) self.assertEqual(ret, expected_buffer) def test_byte_adaptor(self): if six.PY2: from StringIO import StringIO buffer = 'nsetools' fbuffer = StringIO(buffer) else: from io import BytesIO buffer = b'nsetools' fbuffer = BytesIO(buffer) ret_file_buffer = byte_adaptor(fbuffer) self.assertIsInstance(ret_file_buffer, six.StringIO)
pprint('Getting Index Quote for Infosys') pprint(nse.get_quote('infy')) pprint('Getting the entire Index List') indices = nse.get_index_list() pprint(indices) pprint('Getting Index Quote for a particular index') pprint(nse.get_index_quote(indices[1])) pprint('Getting Index Quote for all indices') for x in indices: pprint(nse.get_index_quote(x)) pprint('Getting all Stock Codes') all_stocks = nse.get_stock_codes() pprint(all_stocks) pprint('Getting Quotes for each stock') for x in all_stocks: pprint(nse.get_quote(x)) pprint('Getting Advances & Declines') pprint(nse.get_advances_declines()) pprint('Getting all Top Gainers') pprint(nse.get_top_gainers()) pprint('Getting all Top Losers') pprint(nse.get_top_losers())
class TestCoreAPIs(unittest.TestCase): def setUp(self): self.nse = Nse() def test_string_representation(self): self.assertEqual(str(self.nse), "Driver Class for National Stock Exchange (NSE)") def test_instantiate_abs_class(self): class Exchange(AbstractBaseExchange): pass with self.assertRaises(TypeError): exc = Exchange() def test_nse_headers(self): ret = self.nse.nse_headers() self.assertIsInstance(ret, dict) def test_nse_opener(self): """ should not raise any exception """ opener = self.nse.nse_opener() def test_build_url_for_quote(self): test_code = "infy" url = self.nse.build_url_for_quote(test_code) # 'test_code' should be present in the url self.assertIsNotNone(re.search(test_code, url)) def test_negative_build_url_for_quote(self): negative_codes = [1, None] with self.assertRaises(Exception): for test_code in negative_codes: url = self.nse.build_url_for_quote(test_code) def test_response_cleaner(self): test_dict = { "a": "10", "b": "10.0", "c": "1,000.10", "d": "vsjha18", "e": 10, "f": 10.0, "g": 1000.10, "h": True, "i": None, "j": u"10", "k": u"10.0", "l": u"1,000.10", } expected_dict = { "a": 10, "b": 10.0, "c": 1000.10, "d": "vsjha18", "e": 10, "f": 10.0, "g": 1000.10, "h": True, "i": None, "j": 10, "k": 10.0, "l": 1000.10, } ret_dict = self.nse.clean_server_response(test_dict) self.assertDictEqual(ret_dict, expected_dict) def test_get_stock_codes(self): sc = self.nse.get_stock_codes() self.assertIsNotNone(sc) self.assertIsInstance(sc, dict) # test the json format return sc_json = self.nse.get_stock_codes(as_json=True) self.assertIsInstance(sc_json, str) # reconstruct the dict from json and compare six.assertCountEqual(self, sc, json.loads(sc_json)) # TODO: use mock and create one test where response contains a blank line # TODO: use mock and create one test where response doesnt contain a csv # TODO: use mock and create one test where return is null # TODO: test the cache feature def test_negative_get_quote(self): wrong_code = "inf" self.assertIsNone(self.nse.get_quote(wrong_code)) def test_get_quote(self): code = "infy" resp = self.nse.get_quote(code) self.assertIsInstance(resp, dict) # test json response json_resp = self.nse.get_quote(code, as_json=True) self.assertIsInstance(json_resp, str) # reconstruct the original dict from json # this test may raise false alarms in case the # the price changed in that very moment. self.assertDictEqual(resp, json.loads(json_resp)) def test_is_valid_code(self): code = "infy" self.assertTrue(self.nse.is_valid_code(code)) def test_negative_is_valid_code(self): wrong_code = "in" self.assertFalse(self.nse.is_valid_code(wrong_code)) def test_get_top_gainers(self): res = self.nse.get_top_gainers() self.assertIsInstance(res, list) # test json response res = self.nse.get_top_gainers(as_json=True) self.assertIsInstance(res, str) def test_get_top_losers(self): res = self.nse.get_top_losers() self.assertIsInstance(res, list) def test_render_response(self): d = {"fname": "vivek", "lname": "jha"} resp_dict = self.nse.render_response(d) resp_json = self.nse.render_response(d, as_json=True) # in case of dict, response should be a python dict self.assertIsInstance(resp_dict, dict) # in case of json, response should be a json string self.assertIsInstance(resp_json, str) # and on reconstruction it should become same as original dict self.assertDictEqual(d, json.loads(resp_json)) def test_advances_declines(self): resp = self.nse.get_advances_declines() # it should be a list of dictionaries self.assertIsInstance(resp, list) # get the json version resp_json = self.nse.get_advances_declines(as_json=True) self.assertIsInstance(resp_json, str) # load the json response and it should have same number of # elements as in case of first response self.assertEqual(len(resp), len(json.loads(resp_json))) def test_is_valid_index(self): code = "CNX NIFTY" self.assertTrue(self.nse.is_valid_index(code)) # test with invalid string code = "some junk stuff" self.assertFalse(self.nse.is_valid_index(code)) # test with lower case code = "cnx nifty" self.assertTrue(self.nse.is_valid_index(code)) def test_get_index_quote(self): code = "CNX NIFTY" self.assertIsInstance(self.nse.get_index_quote(code), dict) # with json response self.assertIsInstance(self.nse.get_index_quote(code, as_json=True), str) # with wrong code code = "wrong code" self.assertIsNone(self.nse.get_index_quote(code)) # with lower case code code = "cnx nifty" self.assertIsInstance(self.nse.get_index_quote(code), dict) def test_get_index_list(self): index_list = self.nse.get_index_list() index_list_json = self.nse.get_index_list(as_json=True) self.assertIsInstance(index_list, list) # test json response type self.assertIsInstance(index_list_json, str) # reconstruct list from json and match self.assertListEqual(index_list, json.loads(index_list_json)) def test_jsadptor(self): buffer = "abc:true, def:false, ghi:NaN, jkl:none" expected_buffer = 'abc:True, def:False, ghi:"NaN", jkl:None' ret = js_adaptor(buffer) self.assertEqual(ret, expected_buffer) def test_byte_adaptor(self): if six.PY2: from StringIO import StringIO buffer = "nsetools" fbuffer = StringIO(buffer) else: from io import BytesIO buffer = b"nsetools" fbuffer = BytesIO(buffer) ret_file_buffer = byte_adaptor(fbuffer) self.assertIsInstance(ret_file_buffer, six.StringIO)
def main(request): nse = Nse() top_gainers = nse.get_top_gainers() top_losers = nse.get_top_losers() r = requests.get( 'https://www.quandl.com/api/v3/datasets/NSE/NIFTY_50.json?api_key=oqf4vFLPo8MrPBGXVjki' ) nifty = r.json() nifty_price = [] nifty_date = [] count = 0 for i in nifty['dataset']['data']: nifty_date.append(i[0]) nifty_price.append(i[1]) if count == 30: break else: count = count + 1 print(nifty_date) w_symbol = [] l_symbol = [] w_price = [] l_price = [] w_hprice = [] l_hprice = [] w_lprice = [] l_lprice = [] w_oprice = [] l_oprice = [] count = 0 for i in top_gainers: w_symbol.append(i['symbol']) w_price.append(i['ltp']) w_hprice.append(i['highPrice']) w_lprice.append(i['lowPrice']) w_oprice.append(i['openPrice']) if count == 2: break else: count = count + 1 count = 0 for i in top_losers: l_symbol.append(i['symbol']) l_price.append(i['ltp']) l_hprice.append(i['highPrice']) l_lprice.append(i['lowPrice']) l_oprice.append(i['openPrice']) if count == 2: break else: count = count + 1 loop1 = zip(w_symbol, w_price, w_hprice, w_lprice, w_oprice) loop2 = zip(l_symbol, l_price, l_hprice, l_lprice, l_oprice) nifty_date = json.dumps(nifty_date) return render( request, 'mainpage.html', { 'loop1': loop1, 'loop2': loop2, 'nifty_price': nifty_price, 'nifty_date': nifty_date })
from .decorators import login_required #Importing Nse from nse tools (make sure to install the package 'nsetools') from nsetools import Nse nse = Nse() from .models import * #Data data = {} #To get the stock codes of all the companies all_stock_codes = nse.get_stock_codes() # #To get the stock codes of top gainer top_gainers_codes = nse.get_top_gainers() @login_required def home(request, code=0): print(request.session['user']) user_obj = user.objects.filter(email=request.session['user']).count() if user_obj: pass else: user.objects.create(email=request.session['user'], cash_balance=Decimal(100000), cash_worth=Decimal(0)) user_obj = user.objects.get(email=request.session['user'])
template = template.replace('****NIFTYPHARMA****', niftypharma) template = template.replace('****NIFTYSMLCP50****', niftysmlcp50) top_stocks = "" bottom_stocks = "" managed_stocks = "" """ <tr> <th>NPTC</th> <td>98.0</td> <td>103.0</td> <td>98.0</td> </tr> """ for top_stock in nse.get_top_gainers(): top_stocks += """ <tr> <th>""" + str(top_stock['symbol']) + """</th> <td>""" + str(top_stock['openPrice']) + """</td> <td>""" + str(top_stock['highPrice']) + """</td> <td>""" + str(top_stock['lowPrice']) + """</td> </tr>""" for top_stock in nse.get_top_losers(): bottom_stocks += """ <tr> <th>""" + str(top_stock['symbol']) + """</th> <td>""" + str(top_stock['openPrice']) + """</td> <td>""" + str(top_stock['highPrice']) + """</td> <td>""" + str(top_stock['lowPrice']) + """</td>