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)
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)
import json nse = Nse() print(nse) while True: main_input = int( input( "\nWhat You Want To Do\n\nPress 1 to Get The List Of Todays Top Gainers\n\nPress 2 to Get The List Of Todays Top Losers\n\nPress 3 to Get index Quote\n\nPress 4 to Get the Information About The Company Stock by Providing the Symbol Of The Stock\n\nPress 5 To Get the List Of Symbols of Every Stock\n\nPress 6 To Get The List Of Advances Declines\n\nPress 7 to get the list of F&O Lot Sizes: " )) index_quote_list = nse.get_index_list() top_gainers = nse.get_top_gainers() top_losers = nse.get_top_losers() all_stock_codes = nse.get_stock_codes() adv_dec = nse.get_advances_declines() lot_sizes = nse.get_fno_lot_sizes() if main_input == 1: print(json.dumps(top_gainers, sort_keys=True, indent=4)) if main_input == 2: print(json.dumps(top_losers, sort_keys=True, indent=4)) if main_input == 3: x = int( input( "\nWhich Type Of Index Quote You Want To See\nPress 1 to get the List Of Index Quote\nPress 2 to Search The Index Quote: " )) if x == 1: print(json.dumps(index_quote_list, sort_keys=True, indent=4))
def create_offline_sheet(bhav_date_name, expiry_month_name): # Constants MONTH_NAMES = ("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC") nsetools = Nse() # Set Bhav Date bhav_month_name = bhav_date_name[2:5] bhav_month = MONTH_NAMES.index(bhav_month_name) + 1 bhav_day = int(bhav_date_name[:2]) bhav_year = int(bhav_date_name[5:]) bhav_date = date(bhav_year, bhav_month, bhav_day) pre_bhav_date = bhav_date - timedelta(10) inception_date = bhav_date - timedelta(400) now_date = datetime.now( ) #now_date.year, now_date.month, now_date.day, now_date.hour, now_date.minute, now_date.second # Get Expiry Date expiry_month = (MONTH_NAMES.index(expiry_month_name) + 1) if expiry_month_name != "" and expiry_month_name.upper( ) != "NA" else now_date.month #expiry_date = get_expiry_date(year=now_date.year, month=expiry_month) # Temp expiry date #expiry_date = get_expiry_date(year=2019, month=8) # Temp expiry_date = date(2019, 9, 26) # Temp expiry_date_format = date(expiry_date.year, expiry_date.month, expiry_date.day).strftime( '%d-%b-%Y') #'29-Aug-2019' # Get Symbols and Lot Sizes and create Sheet fno_lot_sizes = nsetools.get_fno_lot_sizes() sheet = pd.DataFrame() sheet['SYMBOL'] = fno_lot_sizes.keys() sheet['Lot'] = fno_lot_sizes.values() ## Temp Dataframe # data = {'Name':['Tom', 'nick', 'krish', 'jack'], 'Age':[20, 21, 19, 18]} # Temp # sheet = pd.DataFrame(data) # Temp #++++++++++++ Sheet Processing for symbol in sheet['SYMBOL']: # Get Futures historical data set Position Values is_index_future = True if symbol == 'BANKNIFTY' or symbol == 'NIFTY' or symbol == 'NIFTYIT' else False futures_data = get_history(symbol=symbol, start=pre_bhav_date, end=bhav_date, futures=True, index=is_index_future, expiry_date=expiry_date) sheet.loc[(sheet['SYMBOL'] == symbol), 'Open'] = float(futures_data[-1:]['Open']) sheet.loc[(sheet['SYMBOL'] == symbol), 'High'] = float(futures_data[-1:]['High']) sheet.loc[(sheet['SYMBOL'] == symbol), 'Low'] = float(futures_data[-1:]['Low']) sheet.loc[(sheet['SYMBOL'] == symbol), 'Close'] = float(futures_data[-1:]['Close']) sheet.loc[(sheet['SYMBOL'] == symbol), 'ClosePrev'] = float(futures_data[-2:-1]['Close']) sheet['%Close'] = (sheet['Close'] / sheet['ClosePrev'] - 1) * 100 sheet.loc[(sheet['SYMBOL'] == symbol), 'OI'] = float(futures_data[-1:]['Open Interest']) sheet.loc[(sheet['SYMBOL'] == symbol), 'OIPrev'] = float(futures_data[-2:-1]['Open Interest']) sheet['%OI'] = (sheet['OI'] / sheet['OIPrev'] - 1) * 100 sheet['OIChg'] = (sheet['OI'] - sheet['OIPrev']) sheet.loc[(sheet['SYMBOL'] == symbol), 'ExpDt'] = expiry_date_format # Set Entry and SL values _buy_entry = max(futures_data[-4:]['High']) * 1.01 _sell_entry = min(futures_data[-4:]['Low']) * .99 _2day_min_low = min(futures_data[-2:]['Low']) _2day_max_high = max(futures_data[-2:]['High']) sheet.loc[(sheet['SYMBOL'] == symbol), 'BuyEntry'] = _buy_entry sheet.loc[(sheet['SYMBOL'] == symbol), 'SellEntry'] = _sell_entry sheet.loc[(sheet['SYMBOL'] == symbol), 'BuySL'] = _2day_min_low if ( _2day_min_low > _buy_entry * .97) else _buy_entry * .97 sheet.loc[(sheet['SYMBOL'] == symbol), 'SellSL'] = _2day_max_high if ( _2day_max_high < _sell_entry * 1.03) else _sell_entry * 1.03 # Get Spot historical data set Moving Averages if not is_index_future: spot_data = get_history(symbol=symbol, start=inception_date, end=bhav_date) sheet.loc[(sheet['SYMBOL'] == symbol), 'StockLast'] = spot_data[-1:]['Last'].mean() sheet.loc[(sheet['SYMBOL'] == symbol), 'MovingAverage50'] = spot_data[-50:]['Last'].mean() sheet.loc[(sheet['SYMBOL'] == symbol), 'MovingAverage100'] = spot_data[-100:]['Last'].mean() sheet.loc[(sheet['SYMBOL'] == symbol), 'MovingAverage200'] = spot_data[-200:]['Last'].mean() # Set Position type sheet.loc[(sheet['%Close'] > 2) & (sheet['%OI'] > 10), 'Position'] = 'Long Buildup' sheet.loc[(sheet['%Close'] < -2) & (sheet['%OI'] > 10), 'Position'] = 'Short Buildup' sheet.loc[(sheet['%Close'] < -2) & (sheet['%OI'] < -10), 'Position'] = 'Long Unwinding' sheet.loc[(sheet['%Close'] > 2) & (sheet['%OI'] < -10), 'Position'] = 'Short Covering' sheet = sheet.fillna('') sheet.loc[sheet['Position'] == 'Long Buildup', 'Strategy'] = 'Buy' sheet.loc[sheet['Position'] == 'Short Covering', 'Strategy'] = 'Buy' sheet.loc[sheet['Position'] == 'Short Buildup', 'Strategy'] = 'Sell' sheet.loc[sheet['Position'] == 'Long Unwinding', 'Strategy'] = 'Sell' sheet = sheet.sort_values(by='Strategy') sheet = sheet.fillna('') # Set Target and Scope sheet['BuyTarget'] = sheet['BuyEntry'] * 1.03 sheet['SellTarget'] = sheet['SellEntry'] * .97 sheet['BuyScope'] = (sheet['BuyEntry'] / sheet['Close'] - 1) * 100 sheet['SellScope'] = (sheet['Close'] / sheet['SellEntry'] - 1) * 100 # Set Pivot, Support and Resistance sheet['Pivot'] = (sheet['High'] + sheet['Low'] + sheet['Close']) / 3 sheet['S3'] = sheet['Low'] - 2 * (sheet['High'] - sheet['Pivot']) sheet['S2'] = sheet['Pivot'] - (sheet['High'] - sheet['Low']) sheet['S1'] = (2 * sheet['Pivot']) - sheet['High'] sheet['R1'] = (2 * sheet['Pivot']) - sheet['Low'] sheet['R2'] = sheet['Pivot'] + (sheet['High'] - sheet['Low']) sheet['R3'] = sheet['High'] + 2 * (sheet['Pivot'] - sheet['Low']) # Set Rating for Moving Average sheet['isAbove50'] = sheet.apply( lambda x: 0.6 if (x['StockLast'] > x['MovingAverage50']) else 0, axis=1) sheet['isAbove100'] = sheet.apply( lambda x: 0.3 if (x['StockLast'] > x['MovingAverage100']) else 0, axis=1) sheet['isAbove200'] = sheet.apply( lambda x: 0.1 if (x['StockLast'] > x['MovingAverage200']) else 0, axis=1) sheet['isBelow50'] = sheet.apply( lambda x: 0.6 if (x['StockLast'] < x['MovingAverage50']) else 0, axis=1) sheet['isBelow100'] = sheet.apply( lambda x: 0.3 if (x['StockLast'] < x['MovingAverage100']) else 0, axis=1) sheet['isBelow200'] = sheet.apply( lambda x: 0.1 if (x['StockLast'] < x['MovingAverage200']) else 0, axis=1) sheet['BuyMovingAverage'] = sheet['isAbove50'] + sheet[ 'isAbove100'] + sheet['isAbove200'] sheet['SellMovingAverage'] = sheet['isBelow50'] + sheet[ 'isBelow100'] + sheet['isBelow200'] # Convert column to datatype float sheet[[ "StockLast", "MovingAverage50", "MovingAverage100", "MovingAverage200" ]] = sheet[[ "StockLast", "MovingAverage50", "MovingAverage100", "MovingAverage200" ]].apply(pd.to_numeric) # Set Buy Ratings sheet['isBuyPosition'] = sheet.apply(lambda x: 1 if ( (x['Position'] == 'Long Buildup') | (x['Position'] == 'Short Covering')) else 0, axis=1) sheet['isOpenLow'] = sheet.apply(lambda x: 1 if (x['Open'] == x['Low']) else 0, axis=1) sheet['isAbovePivot'] = sheet.apply(lambda x: 1 if (x['StockLast'] > x['Pivot']) else 0, axis=1) sheet['isBuyEntryHit'] = sheet.apply(lambda x: 1 if (x['Close'] >= x['BuyEntry']) else 0, axis=1) sheet['BuyRating'] = sheet['BuyMovingAverage'] + sheet[ 'isBuyPosition'] + sheet['isOpenLow'] + sheet['isAbovePivot'] + sheet[ 'isBuyEntryHit'] # Set Sell Ratings sheet['isSellPosition'] = sheet.apply(lambda x: 1 if ( (x['Position'] == 'Short Buildup') | (x['Position'] == 'Long Unwinding')) else 0, axis=1) sheet['isOpenHigh'] = sheet.apply(lambda x: 1 if (x['Open'] == x['High']) else 0, axis=1) sheet['isBelowPivot'] = sheet.apply(lambda x: 1 if (x['StockLast'] < x['Pivot']) else 0, axis=1) sheet['isSellEntryHit'] = sheet.apply( lambda x: 1 if (x['Close'] <= x['SellEntry']) else 0, axis=1) sheet['SellRating'] = sheet['SellMovingAverage'] + sheet[ 'isSellPosition'] + sheet['isOpenHigh'] + sheet[ 'isBelowPivot'] + sheet['isSellEntryHit'] # Rename, Align & Round up Sheet sheet.rename(columns={ 'BuyEntry': '↑Entry', 'BuyTarget': '↑Tgt', 'BuySL': '↑SL', 'BuyScope': '↑Scope', 'BuyRating': '↑Rtg', 'SellEntry': '↓Entry', 'SellTarget': '↓Tgt', 'SellSL': '↓SL', 'SellScope': '↓Scope', 'SellRating': '↓Rtg', 'BuyMovingAverage': '↑MAvg', 'isAbovePivot': '↑Pvot', 'isOpenLow': '↑OpnLo', 'isBuyPosition': '↑Posn', 'isBuyEntryHit': '↑HitEnt', 'SellMovingAverage': '↓MAvg', 'isBelowPivot': '↓Pvot', 'isOpenHigh': '↓OpnHi', 'isSellPosition': '↓Posn', 'isSellEntryHit': '↓HitEnt' }, inplace=True) # Align sheet['LTP'] = sheet['Close'] sheet['OInt'] = sheet['OI'] sheet['%chOI'] = sheet['%OI'] sheet = sheet[[ 'SYMBOL', 'Lot', 'LTP', '↑Rtg', '↑Scope', '↑Entry', '↑Tgt', '↑SL', '↓Rtg', '↓Scope', '↓Entry', '↓Tgt', '↓SL', 'Position', 'OInt', '%chOI', '↑MAvg', '↑Pvot', '↑OpnLo', '↑Posn', '↓MAvg', '↓Pvot', '↓OpnHi', '↓Posn', '↑HitEnt', '↓HitEnt', 'Open', 'High', 'Low', 'Close', 'ClosePrev', '%Close', 'OI', 'OIPrev', '%OI', 'OIChg', 'StockLast', 'MovingAverage50', 'MovingAverage100', 'MovingAverage200', 'S3', 'S2', 'S1', 'Pivot', 'R1', 'R2', 'R3', 'isAbove50', 'isAbove100', 'isAbove200' ]] # Decimal round up sheet = sheet.round(1) # Sort sheet to view Bullish symbols sheet.sort_values(['↑Scope', '↑Rtg', '↑Posn'], ascending=[True, False, False], inplace=True) # Sort sheet to view Bearish symbols #sheet.sort_values(['↓Scope', '↓Rtg', '↓Posn'], ascending=[True, False, False], inplace=True) return sheet
df_stock_codes=pd.DataFrame(all_stock_codes.items(), columns=['SYMBOL', 'NAME OF COMPANY']) index_codes = nse.get_index_list() pprint(index_codes) df_index_codes=pd.DataFrame(index_codes) adv_dec = nse.get_advances_declines() pprint(adv_dec) top_gainers = nse.get_top_gainers() df_topgainers=pd.DataFrame(top_gainers) df_topgainers_info=df_topgainers.loc[:,['symbol','openPrice','highPrice','ltp']] top_losers = nse.get_top_losers() df_toplosers=pd.DataFrame(top_losers) df_toplosers_info=df_toplosers.loc[:,['symbol','openPrice','highPrice','ltp']] a=nse.get_fno_lot_sizes() #To get the lot size for future and option market df_lot_size=pd.DataFrame(a.items(),columns=['fstock','Lot_size']) """" url = 'https://www.nseindia.com/content/indices/ind_nifty50list.csv' s = requests.get(url).content #df1= pd.read_csv(io.StringIO(s.decode('utf-8'))) #d=get_history(df1.INFY ,start=date(2020,1,1), end=date(2020,3,20)) #a= nse.get_quote(‘infy’ , as_json=True) """
def get_fno_items(): nse = Nse() fno_items = nse.get_fno_lot_sizes() df = pd.DataFrame.from_dict(fno_items, orient='index') df.index.rename('symbol', inplace=True) return df