Exemplo n.º 1
0
def index(request,code=None):
    # return HttpResponse('Hello from Python!')
    nse = Nse()
    if nse.is_valid_code(code):
        print code
        q = nse.get_quote(str(code))
        return JsonResponse(q)

    return HttpResponse("not valide")
Exemplo n.º 2
0
def getstockList():
    nse = Nse()
    all_stock_code = nse.get_stock_codes(cached=True)
    all_stock_codes = pd.DataFrame(list(all_stock_code.items()),
                                   columns=["SYMBOL", "NAME OF COMPANY"])
    all_stock_codes.drop(all_stock_codes.index[0], inplace=True)
    Symbols = all_stock_codes['SYMBOL'].tolist()
    isvalid = list(map(lambda x: nse.is_valid_code(x), Symbols))
    all_stock_codes['isactve'] = isvalid
    all_stock_codes['FUT'] = False
    all_stock_codes['IDX'] = False
    return all_stock_codes
Exemplo n.º 3
0
class Utility:
    def __init__(self):
        self.nse = Nse()

    def CheckStockCode(self, stock):
        return self.nse.is_valid_code(stock)

    def GetAllDetailsOfStock(self, stock):
        return self.nse.get_quote(str(stock))

    def GetAllAttrNamesOfStock(self, stock):
        return self.nse.get_quote(stock).keys()

    def CheckAttrNamesOfStock(self, stock, attrnames):
        ret = self.GetAllDetailsOfStock(stock)
        if set(attrnames).issubset(set(ret.keys())):
            return True
        else:
            return False

    def CheckAttrTypesOfStock(self, stock, attrnames, attrtypes, attrvalues):
        ret = self.GetAllDetailsOfStock(stock)
        flag = False
        for i in range(len(attrtypes)):
            if str(attrtypes[i]) == 'date':
                try:
                    parse(ret[attrnames[i]])
                    parse(str(attrvalues[i]))
                    flag = True
                except:
                    flag = False
                    break

            elif str(attrtypes[i]) == 'number':
                try:
                    float(ret[attrnames[i]])
                    float(str(attrvalues[i]))
                    flag = True
                except:
                    flag = False
                    break
            else:
                flag = True

        return flag

    def CheckOperation(self, attrtype, operation):

        if attrtype == 'string' and operation != 'equals':
            return False
        else:
            return True
Exemplo n.º 4
0
def stock_price(symbol):
    """
    This function returns the last
	price of the given symbol.
	None if the symbol is not valid.
	"""
    nse = Nse()
    if nse.is_valid_code(symbol):
        q = nse.get_quote(symbol)
        return q.get('lastPrice', None)
    else:
        sym = symbolmatcher.findSymbol(symbol)
        if sym is not None:
            q = nse.get_quote(sym)
            return q.get('lastPrice', None)
        else:
            logger.error("Unknown symbol " + symbol)
            return None
Exemplo n.º 5
0
def process(input,entities):
    output = {}
    try:
        nse = Nse()
        symbol = " "
        #  symbol is the 'NSE symbol of the company'
        s= input.split(' ')
        for i in s:
            if nse.is_valid_code(str(i)):
                symbol = i
                break

        q = nse.get_quote(str(symbol))
        #  Getting Company name using variable symbol
        company_name  = q['companyName']
        company_symbol = q['symbol']
        # Getting open price of the day
        open_price = q['open']
        # Getting closing price of the day
        close_price = q['closePrice']
        # Getting average price of the day
        stock_price = q['faceValue']
        # Top gainers  for the last trading session
        # Top losers for the last trading session

        output['input'] = "Stock_price"
        msg = 'Company Name = '+company_name+" \n "+"Symbol = "+company_symbol+"\n "+"Open Price = "+str(open_price)+"\n"+"Close Price = "+str(close_price)+"\n"+"Stock Price = "+str(stock_price)
        msg_1={'text':msg}

        msg_1= add_quick_reply(msg_1, 'wipro stock', modules.generate_postback('stock_price'))
        msg_1 = add_quick_reply(msg_1, 'Tell me a joke.', modules.generate_postback('joke'))
        msg_1 = add_quick_reply(msg_1, 'roll a dice.', modules.generate_postback('dice'))
        output['output']=msg_1
        output['success']=True
    except:
        error_message = 'I couldn\'t understand the symbol '
        error_message += '\nPlease ask something like tcs stock_price etc.'
        output['error_msg'] = TextTemplate(error_message).get_message()
        output['success'] = False

    return output
Exemplo n.º 6
0
def transform(row):
    stockName = row[0]
    quantity = float(row[1])
    avgPrice = float(row[2])

    currVal = quantity * avgPrice

    nse = Nse()
    if nse.is_valid_code(stockName):
        nseStock = nse.get_quote(stockName)
        #daychange = ((float(nseStock["change"]) / nseStock['basePrice']) * 100)
        PL = (float(nseStock["lastPrice"]) - avgPrice) * quantity
        PL_per = (float(nseStock["lastPrice"]) - avgPrice) / avgPrice * 100
        exDate = nseStock["exDate"]
        #       if str(exDate=='None'):
        #            exDate=str("24-SEP-01")
        return [
            stockName,
            int(quantity), avgPrice, nseStock["lastPrice"],
            "%.2f" % currVal,
            "%.2f" % PL,
            "%.2f" % PL_per,
            "%.2f" % float(nseStock["pChange"]), nseStock["dayHigh"],
            nseStock["pricebandupper"], nseStock["pricebandlower"],
            nseStock["deliveryQuantity"], nseStock["totalTradedVolume"],
            nseStock["varMargin"], nseStock["high52"], nseStock["low52"],
            stockName + nseStock["purpose"], exDate
        ]

    else:
        ltp = row[3]
        currVal = row[4]
        PL = row[5]
        PL_per = row[6]
        dayChg = row[7]
        return [
            stockName,
            int(quantity), avgPrice, ltp, currVal, PL, PL_per, dayChg, "NA",
            "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
            str("24-SEP-01")
        ]
Exemplo n.º 7
0
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_nse_headers(self):
        ret = self.nse.nse_headers()
        self.assertIsInstance(ret, dict)

    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_get_peer_companies(self):
        code = 'infy'
        response = self.nse.get_peer_companies(code)
        self.assertIsInstance(response, pd.DataFrame)

        # This one was causing a weird error. as the offset was different
        code = '63moons'
        response = self.nse.get_peer_companies(code)
        self.assertIsInstance(response, pd.DataFrame)

    def test_market_status(self):
        result = market_status()
        self.assertIsInstance(result, bool)

    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, pd.DataFrame)
        if sc.empty:
            self.fail()


# 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.assertEqual(self.nse.get_quote(wrong_code), None)

    def test_get_quote(self):
        resp = self.nse.get_quote('infy', '20Microns', 'abb')
        self.assertEqual(len(resp), 3)
        self.assertIsInstance(resp, pd.DataFrame)
        # test json response
        json_resp = self.nse.get_quote('infy',
                                       '20Microns',
                                       'abb',
                                       as_json=True)
        self.assertEqual(len(json_resp), 3)
        self.assertIsInstance(json_resp[0], str)

    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(self):
        # as_json = False
        # This test will remove the need to test the individual parts
        result = self.nse.get_top('gainers', 'losers', 'volume', 'active',
                                  'advances decline', 'index list', 'JUNK')
        # Gainers/Losers/Volume/Advances Decline is supposed to return a list of dictionaries
        # Index list is supposed to return a list of strings
        # JUNK Should not return anything
        temp = []
        for item in result:
            temp.append(item)

        self.assertEqual(6, len(temp))
        gainer, loser, volume, active, adv_decline, index_list = temp[0], temp[
            1], temp[2], temp[3], temp[4], temp[5]

        # Test these individually
        self.assertIsInstance(gainer, pd.DataFrame)

        self.assertIsInstance(loser, pd.DataFrame)

        self.assertIsInstance(volume, pd.DataFrame)

        self.assertIsInstance(adv_decline, pd.DataFrame)

        self.assertIsInstance(index_list, list)

        # Now as_json = True
        result = self.nse.get_top('gainers',
                                  'losers',
                                  'volume',
                                  'active',
                                  'advances decline',
                                  'index list',
                                  as_json=True)

        temp = []
        for item in result:
            temp.append(item)

        self.assertEqual(6, len(temp))
        gainer, loser, volume, active, adv_decline_json, index_list_json = temp[
            0], temp[1], temp[2], temp[3], temp[4], temp[5]

        self.assertIsInstance(gainer, str)
        self.assertIsInstance(loser, str)
        self.assertIsInstance(volume, str)
        self.assertIsInstance(active, str)

        self.assertIsInstance(adv_decline_json, str)
        self.assertEqual(len(adv_decline), len(json.loads(adv_decline_json)))

        self.assertIsInstance(index_list_json, str)
        self.assertListEqual(index_list, json.loads(index_list_json))

    def test_render_response(self):
        d = {'fname': 'Arkoprabho', 'lname': 'Chakraborti'}
        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_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_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):
        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_save_file(self):
        # Call the function, check if the file has been saved at the required location
        dataframe = self.nse.get_stock_codes()
        save_file(dataframe, 'csv', path=gettempdir(), name='StockCodes')
        path = os.path.join(gettempdir(), 'StockCodes.csv')
        if not os.path.exists(path):
            self.fail()

        save_file(dataframe, 'html', path=gettempdir(), name='StockCodes')
        path = os.path.join(gettempdir(), 'StockCodes.html')
        if not os.path.exists(path):
            self.fail()

        save_file(dataframe, 'json', path=gettempdir(), name='StockCodes')
        path = os.path.join(gettempdir(), 'StockCodes.json')
        if not os.path.exists(path):
            self.fail()

        save_file(dataframe, 'tex', path=gettempdir(), name='StockCodes')
        path = os.path.join(gettempdir(), 'StockCodes.tex')
        if not os.path.exists(path):
            self.fail()
Exemplo n.º 8
0
class ManagerLib(object):

    _instance = None

    def __new__(self):
        if not self._instance:
            self._instance = super(ManagerLib, self).__new__(self)
            self.nse = Nse()
            self.userList = []
        return self._instance

    #def __init__(self):
    #self.nse = Nse()
    #self.userList = []

    def GetLiveData(self, key, id, stock):
        ret = self.GetUser(key, id)
        if isinstance(ret, UserDetails):
            ret = self.nse.get_quote(str(stock))
        return json.dumps(ret,
                          default=lambda o: o.__dict__,
                          sort_keys=True,
                          indent=4)

    def CheckStockCode(self, key, id, stock):
        ret = self.GetUser(key, id)
        if isinstance(ret, UserDetails):
            ret = self.nse.is_valid_code(str(stock))
        return json.dumps(ret,
                          default=lambda o: o.__dict__,
                          sort_keys=True,
                          indent=4)

    def GetListOfStocks(self, key, id):
        ret = self.GetUser(key, id)
        if isinstance(ret, UserDetails):
            ret = self.nse.get_stock_codes()
        return json.dumps(ret,
                          ensure_ascii=False,
                          default=lambda o: o.__dict__,
                          sort_keys=True,
                          indent=4)

    def AddUser(self, key, firebase_url, firebase_pass):
        firebaseauth = {
            'FIREBASE_URL': firebase_url,
            'FIREBASE_PWD': firebase_pass
        }
        userdetailobj = UserDetails(key, firebaseauth)
        self.userList.append(userdetailobj)
        ret = {
            'message': 'User added successfully.',
            'id': userdetailobj.userid
        }
        return json.dumps(ret,
                          default=lambda o: o.__dict__,
                          sort_keys=True,
                          indent=4)

    def GetUsers(self):
        return json.dumps(self.userList,
                          default=lambda o: o.__dict__,
                          sort_keys=True,
                          indent=4)

    def GetUser(self, key, id):
        userobj = list(x for x in self.userList if x.userid == id)
        if userobj:
            if userobj[0].userkey == key:
                return userobj[0]
            else:
                return {'error': 'Id-key mismatch'}
        else:
            return {'error': 'Id not found'}

    def GetUserDetails(self, key, id):
        ret = self.GetUser(key, id)
        return json.dumps(ret,
                          default=lambda o: o.__dict__,
                          sort_keys=True,
                          indent=4)

    def AddConditionFieldList(self, key, id, indice, attrnames, attrtypes,
                              attrvalues, conjunctions, operations):
        ret = self.GetUser(key, id)
        if isinstance(ret, UserDetails):
            ret = ret.SetConditionList(indice, attrnames, attrtypes,
                                       attrvalues, conjunctions, operations)
        return json.dumps(ret,
                          default=lambda o: o.__dict__,
                          sort_keys=True,
                          indent=4)

    def AddSubscibeFieldList(self, key, id, conditionid, subscribeFieldlist,
                             triggermessage):
        ret = self.GetUser(key, id)
        if isinstance(ret, UserDetails):
            conditionobjlist = list(condition
                                    for condition in ret.conditionList
                                    if condition.id == conditionid)
            if conditionobjlist:
                if not any(subscription
                           for subscription in ret.subscribeFieldList
                           if subscription.id == conditionid):
                    ret = ret.SetSubscibeFieldList(conditionobjlist[0].id,
                                                   conditionobjlist[0].indice,
                                                   subscribeFieldlist,
                                                   triggermessage)

                else:
                    ret = {
                        'error':
                        'Subscription for the condition already present.Remove and then try.'
                    }
            else:
                ret = {'error': 'Condition id not found.'}

        return json.dumps(ret,
                          default=lambda o: o.__dict__,
                          sort_keys=True,
                          indent=4)

    def RemoveFromConditionList(self, key, id, conditionid):
        ret = self.GetUser(key, id)
        if isinstance(ret, UserDetails):
            ret = ret.RemoveFromConditionList(conditionid)
        return json.dumps(ret,
                          default=lambda o: o.__dict__,
                          sort_keys=True,
                          indent=4)

    def RemoveFromSubscriptionList(self, key, id, subscriptionid):
        ret = self.GetUser(key, id)
        if isinstance(ret, UserDetails):
            ret = ret.RemoveFromSubscriptionList(subscriptionid)
        return json.dumps(ret,
                          default=lambda o: o.__dict__,
                          sort_keys=True,
                          indent=4)

    def GetConditionList(self, key, userid):
        ret = self.GetUser(key, id)
        if isinstance(ret, UserDetails):
            ret = ret.conditionList
        return json.dumps(ret,
                          default=lambda o: o.__dict__,
                          sort_keys=True,
                          indent=4)

    def GetSubscriptionList(self, key, userid):
        ret = self.GetUser(key, id)
        if isinstance(ret, UserDetails):
            ret = ret.subscribeFieldList
        return json.dumps(ret,
                          default=lambda o: o.__dict__,
                          sort_keys=True,
                          indent=4)

    def RemoveUser(self, key, id):
        ret = self.GetUser(key, id)
        if isinstance(ret, UserDetails):
            self.userList.remove(ret)
            ret = {'message': 'User removed successfully'}

        return json.dumps(ret,
                          default=lambda o: o.__dict__,
                          sort_keys=True,
                          indent=4)

    def GetADByStockCode(self, stocklist):
        AllAD = self.nse.get_advances_declines()
        ret = list(x for x in AllAD if x['indice'] in stocklist)
        return ret

    def GetAllADStockCode(self):
        AllAD = self.nse.get_advances_declines()
        return list(x['indice'] for x in AllAD)

    def CheckAttrNameOfStock(self, stock, attrname):
        ret = GetAllDetailsOfStock(self, stock)
        if attrname in ret:
            return True
        else:
            return False

    def CheckAttrTypeOfStock(self, stock, attrname, attrtype):
        ret = GetAllDetailsOfStock(self, stock)
        if attrtype == 'date':
            try:
                parse(ret[attrname])
                return True
            except:
                return False

        elif attrtype == 'number':
            try:
                float(ret[attrname])
                return True
            except:
                return False
        else:
            return True

    def CheckOperation(self, attrtype, operation):
        if attrtype == 'string' and operation != 'equals':
            return False
        else:
            return True

    def SetStockList(self, stocklist):
        self.stocklist = stocklist

    def GetStockList(self):
        return self.stocklist

    def AddStock(self, stock):
        self.stocklist.append(stock)

    def RemoveStock(self, stock):
        if len(self.stocklist) > 0 and stock in self.stocklist:
            self.stocklist.remove(stock)
Exemplo n.º 9
0
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)
Exemplo n.º 10
0
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)
Exemplo n.º 11
0
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))
Exemplo n.º 12
0
#import nsetools
from nsetools import Nse
nse = Nse()
print(nse)

q = nse.get_quote('infy')  # it's ok to use both upper or lower case for codes.
from pprint import pprint  # just for neatness of display
pprint(q)

nifty_quote = nse.get_index_quote(
    'cnx nifty')  # code can be provided in upper|lower case.
banknifty_quote = nse.get_index_quote(
    'banknifty')  # code can be provided in upper|lower case.
pprint(nifty_quote)

pprint(banknifty_quote)

all_stock_codes = nse.get_stock_codes()
pprint(all_stock_codes)

index_codes = nse.get_index_list()
pprint(index_codes)

adv_dec = nse.get_advances_declines()
pprint(adv_dec)

top_gainers = nse.get_top_gainers()
pprint(top_gainers)

nse.is_valid_code('infy')  # this should return True
Exemplo n.º 13
0
    # get total number of rows
    print("Total no. of Holding: %d" % (csvreader.line_num))

# printing the field names
#print('Field names are:\n' + ', '.join(field for field in fields))
investment = 0
totalinvestment = 0

for row in rows[:]:
    # parsing each column of a row
    stockName = row[0]
    quantity = float(row[1])
    avgPrice = float(row[2])
    investment = quantity * avgPrice
    totalinvestment += investment
    if nse.is_valid_code(stockName):
        nseStock = nse.get_quote(stockName)
        daychange = ((float(nseStock["change"]) / nseStock['basePrice']) * 100)
        PL = (float(nseStock["lastPrice"]) - avgPrice) * quantity
        table.add_row([
            stockName, quantity, avgPrice, nseStock["lastPrice"], investment,
            PL, daychange
        ])

print("-------Total Investment---------=", totalinvestment)
print(table)
nse = Nse()
print(nse)


def printStocks(stocks):
class Stocks:
    def __init__(self):
        self.nse = Nse()
        self.client = pymongo.MongoClient(
            f"mongodb+srv://rachitahuja20:{DB_PASS}@cluster0.toqqc.mongodb.net/Cluster0?retryWrites=true&w=majority"
        )
        self.db = self.client.Stocks
        self.bulk = self.db.Stocks_Historical.initialize_unordered_bulk_op()

    def get_stock_value(self, ticker):

        if self.nse.is_valid_code(ticker):
            try:
                q = self.nse.get_quote(ticker)
                lastprice = q["lastPrice"]
                return lastprice
            except:
                return None
        else:
            return None

    def get_request(self, url, headers, timeout=(5, 25)):
        start_time = time.time()
        response = requests.get(url, timeout=timeout, headers=headers)
        end_time = time.time() - start_time
        return {'responsetime': end_time, 'response': response.text}

    def lastTradedPrice(self, ticker):
        url = 'https://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/GetQuote.jsp?symbol=' + ticker + '&illiquid=0&smeFlag=0&itpFlag=0'.format(
            ticker)

        # url = "https://httpbin.org/user-agent"
        headers = {
            'User-Agent':
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36',
            "accept": "application/json"
        }
        try:
            data_dict = self.get_request(url=url, headers=headers)

            soup = BeautifulSoup(data_dict["response"], 'html.parser')

            text = soup.find_all(id="responseDiv")[0].get_text()

            LTP = re.search('(?<="lastPrice":).*?(?=}])',
                            text).group(0).replace('"', '')

            return LTP

        except Exception as e:
            print("error", e)

    def today_date(self):
        date = datetime.datetime.today().strftime("%d-%m-%Y")
        return date

    def Mongo_Data_Push(self, ticker):

        #data = self.lastTradedPrice(ticker)
        data = self.get_stock_value(ticker)
        date = str(self.today_date())

        if data is not None:

            self.bulk.find({"SYMBOL": ticker}).update({"$set": {date: data}})

    def pipeline(self, ticker):

        self.Mongo_Data_Push(ticker)

    def get_list(self):

        doc = self.db.Nse_Stocks_List.find()
        for docs in doc:
            return docs["List"]
Exemplo n.º 15
0
#logging.debug('A debug message!')
#logging.info('A debug message!')
#logging.critical('This is a critical message')

if argnum != 2:
	logging.info('More than one argument to script. Currently not supported')	
	print('');
	exit();

logging.info('Attempting to fetch quotes for ' + scrip + '...');

from nsetools import Nse
nse = Nse()

if nse.is_valid_code(scrip):
	logging.info('Scrip name is valid')
	#Add Success attrib in JSON
	q=nse.get_quote(scrip, as_json=True)
	#q = '{ }';
	quotedata = json.loads(q)
	quotedata['Success'] = 1;
	#Add timestamp:
	#quote_time =  datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S+0000");

	T_UTC = datetime.utcnow()
	T_in  = T_UTC + timedelta(hours=5, minutes=30)
	quote_time =  T_in.strftime("%s");
	quotedata['timestamp'] = quote_time;
	q=json.dumps(quotedata);
	print(q)
Exemplo n.º 16
0
import nsepy

from nsetools import Nse
nse = Nse()
print(nse)

all_stock_codes = nse.get_stock_codes(cached=True)
print(all_stock_codes)

index_codes = nse.get_index_list(cached=True)
top_gainers = nse.get_top_gainers()
nse.is_valid_code('infy')

print(index_codes)
Exemplo n.º 17
0
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)
Exemplo n.º 18
0
df_info['Persistent']=Persistent
df_info['Cipla']=Cipla
df_info['Titan']=Titan
df_info['Sunpharma']=sunpharma
df_info['Hdfc']=Hdfc
df_info.rename(index={0:'dayLow',1:'dayHigh',2:'Open'}, inplace=True)
df_info=df_info.T
"""""
df_info['open']=q['open']
df_info['dayHigh']=q['dayHigh']
df_info['dayLow']=q['dayLow']
df_info['close']= q['closePrice']
"""


nse.is_valid_code('infy') # this should return True True
nse.is_valid_code('innnfy') # should return False False

nse.is_valid_index('cnx nifty') # should return True True
nse.is_valid_index('cnxnifty') # should return False False


nse.get_index_list()
nse.get_index_quote("nifty bank")
all_stock_codes = nse.get_stock_codes()
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)