Esempio n. 1
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
Esempio n. 2
0
class getQuotes:
    def __init__(self, symbol):
        self.nse = Nse()
        self.symbol = symbol
        self.stocknamelist = []
        self.closepricelist = []
        self.yearhighlist = []
        self.yearlowlist = []

    def run(self):
        import requests
        requests.packages.urllib3.disable_warnings()
        import ssl

        try:
            _create_unverified_https_context = ssl._create_unverified_context
        except AttributeError:
            pass
        else:
            ssl._create_default_https_context = _create_unverified_https_context

        for i in self.symbol:
            q = self.nse.get_quote(i)
            closedprice = q.get("averagePrice")
            self.closepricelist.append(closedprice)
            companyName = q.get("companyName")
            self.stocknamelist.append(companyName)
            yearlyhigh = q.get("high52")
            self.yearhighlist.append(yearlyhigh)
            yearlylow = q.get("low52")
            self.yearlowlist.append(yearlylow)
Esempio n. 3
0
def nse_stock_current_data(symbol):
    try:
        nse = Nse()

        print("Collecting Current Stock Data", "-" * 80)
        print("date and time: ", datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
        stock = nse.get_quote(symbol)
        print("date and time: ", datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
        print("Current Stock Data Collected", "-" * 80)

        stock_price = {
            "date":
            "{}-{}-{}".format(date.today().day,
                              date.today().month,
                              date.today().year),
            "price":
            stock['lastPrice'],
        }
        return Response(mimetype="application/json",
                        response=json.dumps(stock_price),
                        status=200)
    except Exception as e:
        error_msg = get_error_msg(e)
        logger.error(error_msg)
        return Response(mimetype="application/json",
                        response=json.dumps({'error': error_msg}),
                        status=400)
Esempio n. 4
0
def get_nse100_data(stock_dict=stock_dict):
    stocks_dict = {}
    nse = Nse()
    stock_parameters = [
        'dayHigh', 'dayLow', 'open', 'lastPrice', 'pChange',
        'totalTradedVolume'
    ]
    for i, stock in enumerate(stock_dict.keys(), 1):
        print(i, stock)

        stock_details = nse.get_quote(stock, as_json=True)
        stocks_dict.setdefault(stock, [])

        for i, parameter in enumerate(stock_parameters):
            stocks_dict[stock].append(json.loads(stock_details)[parameter])
    df = pd.DataFrame.from_dict(stocks_dict,
                                orient='index',
                                columns=[
                                    'HIGH', 'LOW', 'OPEN', 'LAST TRADED PRICE',
                                    '%change', 'TOTAL TRADED VOLUME'
                                ])
    df.reset_index(inplace=True)
    df.rename(columns={'index': 'symbol'}, inplace=True)
    minute = time.ctime().split(':')[1]
    file_name = 'data.csv'
    file_name = minute + '_' + file_name
    path = './vwap_data/' + file_name
    df.to_csv(path, index=False)
    return df
Esempio n. 5
0
def watchlist(request):
    investedtot = 0
    currentval = 0
    pltot = 0
    returnper = 0
    #stock_list = nse_m_stocklist.objects.exclude(stock_type = 'PL')
    stock_list = nse_m_stocklist.objects.filter(stock_type='WL')
    for stock in stock_list:
        stockprice = 0
        nse = Nse()
        try:
            q = nse.get_quote(stock.stock_code)
            for price in q.items():
                if price[0] == 'lastPrice':
                    stockprice = price[1]
                    break

        except:
            stockprice = 0
        stock.currprice = stockprice
        stock.save()

# table_data = nse_m_stocklist.objects.exclude(stock_type = 'PL')
    table_data = nse_m_stocklist.objects.filter(stock_type='WL')
    table = nse_t_watchlist(table_data)
    RequestConfig(request).configure(table)
    context = {'table': table}
    return render(request, 'nse/watchlist.html', context)
Esempio n. 6
0
def stockInfo():
    name = ""
    price = ""
    symbol = ""

    exchange = input("Enter I for NSE and A for NASDAQ: ")
    symbol = input("Enter brand symbol: ")

    if "I" in exchange or "i" in exchange:
        nse = Nse()
        quote = nse.get_quote(symbol)
        price = (quote['basePrice'])
        price = "INR " + str(price)
        name = quote['companyName']

    elif "A" in exchange or "a" in exchange:
        name = yf.Ticker(symbol)
        name = (name.info['longName'])
        price = stock_info.get_live_price(symbol)
        price = "USD " + str(price)

    else:
        print("Error")

    print("Name   : " + name)
    print("Symbol : " + symbol)
    print("Price  : " + price)
    update_histroy(("checked stock info for"+name))
Esempio n. 7
0
def home(request):
    # in home we are going to create a request to make connection with an API
    import requests  # get data from internet source # pip install requests in Git Bash
    import json  # java script object notation for parsing the requested data

    #	return render(request, 'home.html',{})

    if request.method == 'POST':
        ticker = request.POST['ticker']
        #tick_val = nse.is_valid_code(ticker)

        #if (nse.is_valid_code(ticker)):
        from nsetools import Nse
        nse = Nse()

        api_request = nse.get_quote(ticker)

        try:  #api = json.loads(api_request.content) # parsing the requested data
            api = api_request
        except Exception as e:
            api = 'Error...'

        return render(request, 'home.html', {'api': api})
        #else:
        #	return render(request, 'home.html',{'ticker':"Enter a Ticker"})
    else:
        return render(request, 'home.html', {'ticker': "Enter a Ticker"})
Esempio n. 8
0
def stocks(request):
    import requests  # get data from internet source # pip install requests in Git Bash
    import json  # java script object notation for parsing the requested data
    from nsetools import Nse

    if request.method == 'POST':
        form = StockForm(request.POST or None)

        if form.is_valid():
            form.save()
            messages.success(request, ("stock added"))
            return redirect('stocks')
    else:
        nse = Nse()
        ticker = stock.objects.all()
        output = []
        for ticker_item in ticker:
            api_request = nse.get_quote(
                str(ticker_item))  # need to pass as String, otherwise error
            try:  #api = json.loads(api_request.content) # parsing the requested data
                api = api_request
                output.append(api)
            except Exception as e:
                api = 'Error...'

        return render(request, 'stocks.html', {
            'ticker': ticker,
            'output': output
        })
Esempio n. 9
0
 def do(self):
     CommonCronJob.logger.info("Going to run stock rate updater cron")
     cnt = 0
     stocks = Stock.objects.all()
     currency = Currency.objects.filter(is_default=True).first()
     nse = Nse()
     try:
         with transaction.atomic():
             models_to_create = []
             for stock in stocks:
                 cnt += 1
                 try:
                     quote = nse.get_quote(stock.code)
                     time.sleep(.300)
                     stock_rate = StockRate(code=stock.code, stock=stock,
                                            rate=quote['basePrice'], currency=currency,
                                            last_updated_on=timezone.now())
                     models_to_create.append(stock_rate)
                     CommonCronJob.logger.info("Completed for {0} - {1}".format(cnt, stock))
                 except Exception as er:
                     CommonCronJob.logger.error("Error for {0} - {1} - {2}".format(cnt, stock, er))
             StockRate.objects.all().delete()
             StockRate.objects.bulk_create(models_to_create)
             CommonCronJob.logger.info("Completed stock rate updater cron")
     except URLError:
         CommonCronJob.logger.error("Unable to connect to nse")
     except DatabaseError:
         CommonCronJob.logger.error("Database error")
     except Exception as e:
         CommonCronJob.logger.error("Error happened")
Esempio n. 10
0
class NSE(Stock):
    STOCK_EXCHANGE_CODE = 'NSE'

    def __init__(self):
        self.nse = Nse()
        super(NSE, self).__init__()
    
    def perform_latest(self, code):
        stock_dict = self.nse.get_quote(str(code))
        if stock_dict is None:
            # cannot rely on quandl apis coz it has some api limits
            self.use_default_transform = True
            return super(NSE, self).perform_latest(code)
        return stock_dict

    def transform(self, data):
        return {
            "date": data['cm_adj_low_dt'],
            "open": data['open'],
            "high": data['dayHigh'],
            "low": data['dayLow'],
            "last": data['lastPrice'],
            "close": data['previousClose'],
            "totalTradeQuantity": data['quantityTraded'],
            "turnover": None,
            "refreshedAt": helper.now()
        }
Esempio n. 11
0
def GetPriceSymbol( ):
    nse = Nse()
    with open(r'C:\\Migration\\EagleEye\\Master\\Trading_Mast_zone2.csv',"r") as csv_file:
         csv_reader = csv.reader(csv_file, delimiter=',')
         #next(csv_reader)
         for lines in csv_reader:
             print("The symbol processing is",lines[0])
             q = nse.get_quote(lines[0].strip())
             parsed_json = json.loads(json.dumps(q))
             l_lastprice=parsed_json['lastPrice']
             #print("The last price is ",l_lastprice)
             l_averagePrice=parsed_json['averagePrice']
             #print("The average price is ",l_averagePrice)
             l_totaltradedvolume=parsed_json['totalTradedVolume']
             #print("The total traded volume is ",l_totaltradedvolume)
             l_max_price_n=parsed_json['dayHigh']
             #print("The max price for the symbol ",l_max_price_n)
             l_min_price_n=parsed_json['dayLow']
             #print("The min price for the symbol ",l_min_price_n)
             l_open_price_n=parsed_json['open']
             #print("The open price for the symbol ",l_open_price_n)
             con = cx_Oracle.connect('EQUITY/EQUITY@localhost/XE')
             cur = con.cursor()
             cur.execute("INSERT INTO daily_nse_movement_trans (symbol,lastprice_n,last_avg_price_n,totaltradedvol_n,max_price_n,min_price_n,open_price_n)  VALUES (:1,:2,:3,:4,:5,:6,:7)" ,(lines[0].strip(),l_lastprice, l_averagePrice,l_totaltradedvolume,l_max_price_n,l_min_price_n,l_open_price_n))
             statement = 'DELETE FROM daily_nse_movement_trans WHERE  EXCEPTION_FLAG_V=:type'
             cur.execute(cur.execute(statement, {'type':'Y'}))
             cur.close()
             con.commit()
             #print("End of the loop ---")
             con.close()
Esempio n. 12
0
def ioc():
    keyword = '$IOC'
    stockSymbol = 'IOC'
    my_result = fetch(keyword, stockSymbol)

    predicted_value = my_result[0]
    trend = my_result[1]

    if (trend == 'Downtrend'):
        sentimentColor = 'red'
        sentimentArrow = 'bottom'
    else:
        sentimentColor = 'green'
        sentimentArrow = 'up'

    nse = Nse()
    q = nse.get_quote('ioc')
    q1 = q['closePrice']
    ioc = pd.read_csv('E:\College\Final Year Project\Dataset\IOC.NS.csv')
    contents = ['Date', 'Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume']
    ioc.columns = contents
    ioc.drop('Adj Close', axis=1, inplace=True)

    tempOpen = ioc['Open']
    openList = tempOpen.tolist()
    tempClose = ioc['Close']
    closeList = tempClose.tolist()
    tempDate = ioc['Date']
    dateList0 = tempDate.tolist()
    dateList = dateList0.reverse()

    trendValue = float(predicted_value) - q1
    if (trendValue > 0):
        color = 'green'
        arrow = 'top'
    if (trendValue < 0):
        color = 'red'
        arrow = 'bottom'

    try:
        graph = pygal.Line()
        graph.title = 'IOC Timeline'

        graph.x_labels = dateList0
        graph.add('Open', openList)
        graph.add('Close', closeList)
        graph_data = graph.render_data_uri()
        return render_template('ioc.html',
                               q=q1,
                               graph_data=graph_data,
                               predicted_value=predicted_value,
                               trend=trend,
                               color=color,
                               arrow=arrow,
                               sentimentColor=sentimentColor,
                               sentimentArrow=sentimentArrow)

    except Exception, e:
        return (str(e))
Esempio n. 13
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")
Esempio n. 14
0
def sendemail(request):
    # check for breakeven price
    import smtplib
    stock_list = nse_m_stocklist.objects.filter(stock_type='WL')
    for stock in stock_list:
        stockprice = 0
        nse = Nse()
        try:
            q = nse.get_quote(stock.stock_code)
            for price in q.items():
                if price[0] == 'lastPrice':
                    stockprice = price[1]
                    break
        except:
            stockprice = 0
        stock.currprice = stockprice
        #    stock.save()
        if (float(stock.currprice) < float(stock.notval1)) and (float(
                stock.currprice) > float(
                    stock.notval3)):  # Buy more notification
            SUBJECT = 'Buy More Notification' + stock.stock_code + '\n'
            BODY = stock.stock_code + ' stock has reached buy more notification \n' + stock.notval1
        if float(stock.currprice) > float(stock.notval2):  # Sell notification
            SUBJECT = 'Sell Notification' + stock.stock_code + '\n'
            BODY = stock.stock_code + ' stock has reached Sell notification Levels \n' + stock.notval2
        if float(stock.currprice) < float(
                stock.notval3):  # Stop Loss notification
            SUBJECT = 'Stop Loss Notification' + stock.stock_code + '\n'
            BODY = stock.stock_code + ' stock has reached Stop Loss notification Levels \n' + stock.notval3

        fromaddr = '*****@*****.**'
        recipients = [
            '*****@*****.**', '*****@*****.**'
        ]
        #toaddrs  = ", ".join(recipients)
        toaddrs = '*****@*****.**'
        #msg = 'Why,Oh why!'

        # Prepare actual message
        #msg = """From: %s\nTo: %s\nSubject: %s\n\n%s
        #""" % (fromaddr, ", ".join(toaddrs), SUBJECT, BODY)
        msg = 'Subject: {}\n\n{}'.format(SUBJECT, BODY)

        username = '******'
        password = '******'
        server = smtplib.SMTP('smtp.gmail.com:587')
        server.ehlo()
        server.starttls()
        server.login(username, password)
        server.sendmail(
            fromaddr,
            toaddrs,
            msg,
        )
        server.quit()

    return redirect('My_Stock_Summary')
Esempio n. 15
0
def summarysheet(request):
    if request.user.is_authenticated():
        investedtot = 0
        currentval = 0
        pltot = 0
        returnper = 0

        stock_list = nse_m_summarysheet.objects.filter(stock_type='SH')
        for stock in stock_list:
            stockprice = 0
            nse = Nse()
            try:
                q = nse.get_quote(stock.stock_code)
                for price in q.items():
                    if price[0] == 'lastPrice':
                        stockprice = price[1]
                        break

            except:
                stockprice = 0
            stock.currprice = stockprice
            stock.currvalue = round(
                (float(stockprice) * float(stock.totbuyqty)), 1)
            stock.buyvalue = round(
                (float(stock.totbuyqty) * float(stock.avgbuyprice)), 1)
            z = int(stock.currvalue) - int(stock.buyvalue)
            stock.realpos = ''
            stock.realpos = int(z)
            investedtot = investedtot + int(stock.buyvalue)
            currentval = currentval + int(stock.currvalue)
            pltot = pltot + stock.realpos  # (currentval - investedtot)
            stock.save()
        try:
            returnper = int((pltot / investedtot) * 100)
        except:
            returnper = 0
        table_data = nse_m_summarysheet.objects.filter(stock_type='SH')
        table_data = table_data.order_by('-stock_code')
        table = nse_t_summarysheet(table_data)
        RequestConfig(request).configure(table)

        # Summary table
        summary_table = nse_t_summary([{
            'invval': investedtot,
            'curval': currentval,
            'retval': pltot,
            'retper': returnper
        }])
        RequestConfig(request).configure(summary_table)

        context = {
            'table': table,
            'table_sum': summary_table,
        }
        return render(request, 'nse/summarysheet.html', context)
    else:
        return HttpResponseRedirect('/login')
Esempio n. 16
0
def myfuc(s):
    from nsetools import Nse
    nse = Nse()
    #list1=[]
    #for x in file:
    q = nse.get_quote(s)
    k = (q['buyPrice1'])
    #list1.append(k)
    return (k)
Esempio n. 17
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
Esempio n. 18
0
def my_main():
    filename = sys.argv[-1]
    nse = Nse()

    sym = 'INFY'

    if (filename == 'getWeeklyMA.py'):
        print('Hello Python')
        print(sym +' : ' + getWMA(sym) + '\n')
        print("------------------------------------------------------------------")
        print("                       Portfolio - Weekly Data  ")
        print("------------------------------------------------------------------")
        print("%4s %15s %5s %8s %8s %8s  %8s %8s %7s"%("No","Symbol", "trend", "20WMA", "     RSI(14)", "    CMP""  52WeekHigh", "  %UpPotential", "%RiskMargin", "Ratio"))
        wma, rsi, cmp, trend = getWMAandRSI(sym, -2.0)
        #print(wma);
        q = nse.get_quote(sym)
        h52 =  q['high52']
        upp = ((h52-cmp)/(cmp))*100.00
        risk = ((cmp-wma)/cmp)*100.00
        ratio = upp/risk
        print("%4s %15s %5s %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f"%(1, sym, trend, wma, rsi, cmp, h52, upp, risk, ratio))
    else:
        # Using readlines()
        file1 = open(filename, 'r')
        Lines = file1.readlines()
        print("------------------------------------------------------------------")
        print("                       Portfolio - Weekly Data  ")
        print("------------------------------------------------------------------")
        print("%4s %15s %5s %8s %8s %8s  %8s %8s %7s"%("No","Symbol", "trend", "20WMA", "     RSI(14)", "    CMP""  52WeekHigh", "  %UpPotential", "%RiskMargin", "Ratio"))
        cnt = 1

        for line in Lines:
            sym = line.strip()
            #print("{} {} {}".format(cnt, sym, getWMA(sym)))
            #print("%4s %15s %8s %8s"%(cnt, sym, getWMA(sym), getRSI(sym)))
            wma, rsi, cmp, trend = getWMAandRSI(sym, -2.0)
            #print(wma);
            q = nse.get_quote(sym)
            h52 =  q['high52']
            upp = ((h52-cmp)/(cmp))*100.00
            risk = ((cmp-wma)/cmp)*100.00
            ratio = upp/risk
            print("%4s %15s %5s %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f"%(cnt, sym, trend, wma, rsi, cmp, h52, upp, risk, ratio))
            cnt += 1
Esempio n. 19
0
def get_stock_details():
    nse = Nse()
    print(
        "{:<10} | {:<7} | {:<7} | {:<7} | {:<7} | {:<7} | {:<7} | {:<6} | {:<7} | {:<10} | {:<2}"
        .format("Symbol", "Avg Price", "LTP", "Open", "High", "Low", "Close",
                "Change", "Prev Close", "Qty Traded", "Market Type"))
    for stock in settings.STOCKS:
        stock_data = nse.get_quote(stock)
        stock_data = extract_stock_data(stock_data)
        print_stock_data(stock_data)
Esempio n. 20
0
class Real_Time_Stock_Data(APIView):

    def __init__(self):

        self.nse = Nse()

    def get(self, request):
        stock_list = []
        dataframe = pd.read_csv(os.path.join(settings.BASE_DIR, 'stock_list.csv'))
        # head = dataframe.head()
        for index, row in dataframe.iterrows():
            stock_dict = {}
            stock_dict['id'] = index + 1
            stock_dict['name'] = row['Company Name']
            stock_dict['index_nm'] = row['Symbol']
            stock_dict['currency'] = "INR"
            stock_dict["market"] = "NSE"
            stock_value = self.nse.get_quote(row['Symbol'])
            # stock_value = self.nse.get_quote(row)
            stock_dict['value'] = str(stock_value['lastPrice'])
            if isinstance(stock_value['pChange'], str) and stock_value['pChange'].find('-') != -1:
                stock_dict['state'] = '-'
                stock_dict['state_value'] = str(stock_value['change'])
                stock_dict['percent_state'] = str(stock_value['pChange']) + "%"
            else:
                stock_dict['state'] = "+"
                stock_dict['state_value'] = str(stock_value['change'])
                stock_dict['percent_state'] = str(stock_value['pChange']) + "%" 
            
            stock_list.append(stock_dict)

        return JsonResponse({"data": stock_list})
		
    def post(self, request):
        
        lastprice_dict = {}
        symbols = dict(request.data)['symbols']
        for index, symbol in enumerate(symbols):

            last_price = self.nse.get_quote(symbol)['lastPrice']
            lastprice_dict[symbol] = last_price

        return JsonResponse(lastprice_dict)
def my_main():
    option = sys.argv[-1]

    nse = Nse()
    [dictLargeCap, dictMidCap, dictSmallCap] = getAllCapStocks(False)

    d = dictLargeCap
    #d = { 'INFY' : 123}

    if (option == '-m'):
        d = dictMidCap
    if (option == '-s'):
        d = dictSmallCap

    cnt = 1
    print(
        "--------------------------------------------------------------------------------------"
    )
    print(
        "                      Screener Portfolio - Weekly Data                                "
    )
    print(
        "--------------------------------------------------------------------------------------"
    )
    print("%4s %15s %5s %8s %8s %8s %8s %8s %8s" %
          ("No", "Symbol", "Trnd", "20WMA", "     RSI(14)", "CMP",
           "  52WeekHigh", "  %UpPotential", "%RiskMargin"))

    df = pd.DataFrame(columns=("No", "Symbol", "Trend", "20WMA", "RSI(14)",
                               "CMP", "52WeekHigh", "%UpPotential",
                               "%RiskMargin"))
    for sym in d:
        print(sym)
        #if sym == 'ADANIGAS':
        #    continue
        wma, rsi, cmp, trnd = getWMAandRSI(sym)
        print(wma, rsi, cmp, trnd)  #  = 0.0, 0.0, 0.0, 'UP'
        #wma, rsi, cmp, trnd  = 0.0, 0.0, 0.0, 'UP'
        if (rsi > 59.9 and rsi < 65):
            #if(rsi > -1.0 ):
            q = nse.get_quote(sym)
            h52 = q['high52']
            upp = ((h52 - cmp) / (cmp)) * 100.00
            risk = ((cmp - wma) / cmp) * 100.00
            print("%4s %15s %5s %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f" %
                  (cnt, sym, trnd, wma, rsi, cmp, h52, upp, risk))
            i = cnt - 1
            df.loc[cnt] = [cnt, sym, trnd, wma, rsi, cmp, h52, upp, risk]
            cnt += 1
    print(
        "--------------------------------------------------------------------------------------"
    )

    df = df.sort_values(by='RSI(14)', ascending=False, na_position='first')
    pprint(df)
Esempio n. 22
0
class NseInitializer:
    def __init__(self):
        self.nse = Nse()

    def get_stock_codes(self):
        all_stock_codes = self.nse.get_stock_codes()
        return all_stock_codes

    def get_quote(self,symbol):
        quote = self.nse.get_quote(symbol)
        return quote
 def fetch_stocks(cls):
     nse = Nse()
     print(nse)
     json_data = StocksData.fetch_ticker_list()
     count = 0
     for (attribute, value) in json_data.items():
         if count == 0:
             count += 1
             continue
         print(attribute, value)
         q = nse.get_quote(attribute)
         AwsMessage.upload_msg(q, AwsMessage.stock_address)
         count += 1
Esempio n. 24
0
def plstatement(request):
    investedtot = 0
    currentval = 0
    pltot = 0
    returnper = 0
    stock_list = nse_m_stocklist.objects.filter(stock_type='PL')
    for stock in stock_list:
        stockprice = 0
        nse = Nse()
        try:
            q = nse.get_quote(stock.stock_code)
            for price in q.items():
                if price[0] == 'lastPrice':
                    stockprice = price[1]
                    break

        except:
            stockprice = 0

        stock.buyvalue = round((float(stock.buyqty) * float(stock.buyprice)),
                               1)
        z = int(float(stock.sellvalue)) - int(stock.buyvalue)
        stock.realpos = ''
        stock.realpos = int(z)
        investedtot = investedtot + int(stock.buyvalue)
        currentval = currentval + int(float(stock.sellvalue))
        pltot = pltot + (currentval - investedtot)
        stock.save()
    try:
        returnper = int((pltot / investedtot) * 100)
    except:
        returnper = 0
    table_data = nse_m_stocklist.objects.filter(stock_type='PL')
    table = nse_t_pllist(table_data)
    RequestConfig(request).configure(table)

    # Summary table
    summary_table = nse_t_summary([{
        'invval': investedtot,
        'curval': currentval,
        'retval': pltot,
        'retper': returnper
    }])
    RequestConfig(request).configure(summary_table)
    context = {
        'table': table,
        'table_sum': summary_table,
    }

    return render(request, 'nse/plstatement.html', context)
Esempio n. 25
0
class NSEDataFetch(Nse):
    def __init__(self):
        self.nse = Nse()
        self.equity_stock_watch_all = "https://www.nse-india.com/live_market/dynaContent/live_watch/stock_watch/niftyStockWatch.json"

    def get_active_monthly(self):
        pprint(self.nse.get_active_monthly())

    def get_quote(self, symbol):
        pprint(self.nse.get_quote(symbol))

    def download_bhavcopy(self, date_string):
        arr = []
        response = self.nse.download_bhavcopy(date_string)
        s = io.StringIO(response.decode('utf-8'))
        headers = s.readlines(1)[0].split(',')
        filename = "BavCopy{}.xlsx".format(datetime.now())
        for line in s:
            fields = map(lambda s: s.strip(), line.split(','))
            columns = list(fields)
            #bad coding here, need to remove the hardcoded values,
            #need to automate this hardcoded value
            arr.append({
                headers[0]: columns[0],
                headers[1]: columns[1],
                headers[2]: columns[2],
                headers[3]: columns[3],
                headers[4]: columns[4],
                headers[5]: columns[5],
                headers[6]: columns[6],
                headers[7]: columns[7],
                headers[8]: columns[8],
                headers[9]: columns[9],
                headers[10]: columns[10],
                headers[11]: columns[11],
                headers[12]: columns[12],
                headers[13]: columns[13]
            })
        pd.read_json(json.dumps(arr)).to_excel(filename)

    def get_equity_stock_watch_live(self):
        response = self.nse._get_json_response_from_url(
            self.equity_stock_watch_all, True)
        filename = "EquityMatketWatch{}.xls".format(datetime.now())
        df = pd.read_json(response)
        df.to_excel(filename)

    def get_stock_codes(self):
        self.nse.get_stock_codes()
Esempio n. 26
0
 def GET(self, nseids):
     print(nseids)
     ids = nseids.split(',')
     nse = Nse()
     pricelist = []
     for nseid in ids:
         details = nse.get_quote(nseid)
         name = details.get('companyName')
         price = details.get('lastPrice')
         pricelist.append({
             'nseid': nseid,
             'Company Name': name,
             'Price': price
         })
     return json.dumps(pricelist)
Esempio n. 27
0
File: utils.py Progetto: ncs-jss/NSE
 def run(self):
     try:
         nse = Nse()
         try:
             rate = nse.get_quote(str(self.code))
             rate = rate['lastPrice']
         except Exception, err:
             print err
             return
         share = stock.objects.get(code=self.code)
         if share.price != rate:
             share.update = share.update + 1
         share.price = rate
         if rate > share.max_price_of_day:
             share.max_price_of_day = rate
         share.save()
         print "sucess"
Esempio n. 28
0
File: utils.py Progetto: ncs-jss/NSE
	    def run(self):
	    	try :
	    		nse = Nse()
	    		try :
	    			rate = nse.get_quote(str(self.code))
	    			rate = rate['lastPrice']
	    		except Exception,err :
	    			print err
	    			return
	    		share = stock.objects.get(code=self.code)
	    		if share.price != rate:
	    			share.update = share.update +1
	    		share.price = rate
	    		if rate > share.max_price_of_day:
	    			share.max_price_of_day = rate
	    		share.save()
	    		print "sucess"
Esempio n. 29
0
def price(code):
	#print("got request")
	#print(code)
	nse = Nse()
	stock_code = nse.get_stock_codes()
	#stocks = ['20MICRONS', '3IINFOTECH','3MINDIA','8KMILES','A2ZINFRA','AARTIDRUGS','AARTIIND']
	dic = {}
	#for code in stocks:
	out = nse.get_quote(code)
	dic[code] = out['lastPrice']
	print(dic)
	with open("sample.json", "w") as outfile: 
	    json.dump(dic, outfile)
	with open('sample.json') as data_file:
		data = json.load(data_file)
	#print(data)
	return data
Esempio n. 30
0
def classes(request):
    nse = Nse()
    a = [
        'ABB', 'DMART', 'BHEL', 'TITAN', 'TATAPOWER', 'INDIGO', 'IDEA', 'MRF',
        'PNB', 'GODREJCP', 'LICHSGFIN', 'JSWSTEEL'
    ]
    price = []
    hprice = []
    lprice = []
    oprice = []
    for i in a:
        q = nse.get_quote(i)
        price.append(q['averagePrice'])
        hprice.append(q['dayHigh'])
        lprice.append(q['dayLow'])
        oprice.append(q['closePrice'])
    loop = zip(a, price, hprice, lprice, oprice)

    return render(request, 'classes.html', {'loop': loop})
Esempio n. 31
0
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
Esempio n. 32
0
#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)
else:
	logging.info('Invalid scrip name. Check https://www.nseindia.com to get correct scrip name.')
	#Create JSON with fail attrib
Esempio n. 33
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)
Esempio n. 34
0
from nsetools import Nse
from pprint import pprint
nse = Nse()
all_stock_codes = nse.get_stock_codes()
pprint(all_stock_codes)

for x in all_stock_codes:
 pprint(nse.get_quote(x))
Esempio n. 35
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))
Esempio n. 36
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)
Esempio n. 37
0
class UpdateData:

	def __init__(self,index):
		self.nse = Nse()
		self.date=date.today()
		self.index = index
		self.stock_data = {}
		self.stock_data = self.init_content()
		if self.stock_data is None:
			self.stock_data={}
			self.update_index()
		#pprint(self.stock_data)
	
	def update_index(self):
		count = 0
		with open(self.index) as myfile:
			for line in myfile:
				if count is not 0: 
					line = line.split(',')
					try:
						self.update_content(line[2])
					except:
						continue
					#self.update_hlc(line[2])
				else : 
					count = 1
		self.save_content()
	#	self.write_update('day')
	
	def get_index():
		return self.index
	def update_content(self,stock):
		try:
			print stock
			data = self.nse.get_quote(stock)
		except:
			raise ValueError
		self.stock_data[stock] = data
	
	def get_content(self,stock):
		return self.stock_data.get(stock)

	def read_dict_from_file(self,dir_name,name):
		extension = 'txt'
		index = NIFTYLIST[self.index]
		filename = BASE_PATH+index+SEPERATOR+dir_name+SEPERATOR+name+'.'+extension
		try:
			if(os.path.isfile(filename)):
				with open(filename) as myfile:
					"+ 1 is done because of 1st line in file " 
					data = json.load(myfile)
					return data
		except:
			raise ValueError
		
	
	def write_dict_to_file(self,dir_name,data,mode,name = None):
		if data is None:
			return
		extension = 'txt'
		index = NIFTYLIST[self.index]
		filename = BASE_PATH+index+SEPERATOR+dir_name+SEPERATOR+name+'.'+extension
		directory = os.path.dirname(filename) 
		if not os.path.exists(directory):
  		  os.makedirs(directory)
  		with open(filename, mode) as outfile:
			json.dump(data, outfile)

	def init_content(self):
		#self.update_index()
		name = 'Stocks Content'
		dir_name= 'Daily'
		return self.read_dict_from_file(dir_name,name)

	def save_content(self):
		name = 'Stocks Content'
		dir_name= 'Daily'
		self.write_dict_to_file(dir_name,self.stock_data,'w',name)
	
	def update_val(self,data,stock):
		change = False
		high = self.stock_data[stock]['dayHigh']
		low = self.stock_data[stock]['dayLow']
		if data['High'] < high:
			    data['High'] = high
			    change = True
		if data['Low'] > low:
			    data['Low'] = low
			    change = True
		return {"Data": data, "Change":change}
		
	def update_hlc(self,stock):
		data = self.read_dict_from_file('HLC',stock)
		change = False
		for key in data:
			val = self.update_val(data[key],stock)
			if val['Change']:
				data[key] = val['Data']
				change = True
		if change:
			self.write_dict_to_file('HLC',data,'w',stock)
			print "Updated ",stock

	def read_update(self,period):
		extension = 'txt'
		filename = BASE_PATH+'update_'+period+'.'+extension
		if(os.path.isfile(filename)):
			with open(filename) as myfile:
				head = list(islice(myfile, 1))
			return head
		else:
			self.write_update(period)
			return self.date
	
	def write_update(self,period):
		extension = 'txt'
		filename = BASE_PATH+'update_'+period+'.'+extension
		with open(filename, 'w') as outfile:
				outfile.write(self.date.strftime('%d-%m-%Y'))
	
	def update(self):
		day_update = self.read_update('day')
		month_update = self.read_update('month')
		day_update = datetime.strptime(day_update[0],'%d-%m-%Y').date()
		month_update = datetime.strptime(month_update[0],'%d-%m-%Y').date()
		flagday = False
		flagmonth =False
		count = 0
		for ind in NIFTYLIST:
			self.index = ind
			index = NIFTYLIST[ind]
			if self.date.day - day_update.day > 0 or self.date.month - day_update.month > 0:
				self.update_index()
				flagday =True
			if self.date.month - month_update.month > 0:
				if self.check_month_change(month_update.month):
					self.update_monthly()	
					shutil.rmtree(BASE_PATH+SEPERATOR+index+SEPERATOR+'HLC')
			  		flagmonth =True
			if flagday:
				self.write_update('day')
				if count ==1:
					return True
			if flagmonth:
				self.write_update('month')
				if count ==1:
					return True
			count = count + 1
		return False	

	def check_month_change(self,udate):
		data = StockData('INFY',self)
		mydate = date.today()
		#html = data.get_historical_data(mydate.strftime('%d-02-%Y'),mydate.strftime('%d-%m-%Y'),'m')
		html = data.get_today_data()
		line =html.split('\n')
		line = line[1].split(',')
		data_date = int(line[0].split('-')[1])
		val = False
		if data_date - udate > 0:
			val= True
		return val

	def update_monthly(self):
		count = 0
		with open(self.index) as myfile:
			for line in myfile:
				if count is not 0: 
					line = line.split(',')
					try:
						stock = StockData(line[2],self)
						stock.save_historical_data('1-1-1976',self.date.strftime('%d-%m-%Y'),'m')
					except:
						continue
					#self.update_hlc(line[2])
				else : 
					count = 1
		#self.write_update('month')

	def return_file_data(self):
		filename = self.index
		if(os.path.isfile(filename)):
			with open(filename) as myfile:
				"+ 1 is done because of 1st line in file " 
				head = list(islice(myfile,1,1000))
				return head
Esempio n. 38
0
def toCsv(stock, name, header=False):
    ts = time.time()
    timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
    transposedEntry = DataFrame(stock.values(), index=stock.keys(), columns=[timeStamp])
    entry = transposedEntry.T
    with open(name+".csv", 'a') as file:
        if header:
           entry.to_csv(file, header=True)
        else:
           entry.to_csv(file, header=False)

#################################################################################################
#Intialize Nse
nse = Nse()

stock_name = raw_input("Enter the stock nse id (eg: infy):")

past_stock_value = nse.get_quote(stock_name)
toCsv(past_stock_value, stock_name, True)

while True:
    time.sleep(1) #assuming this delay will come from network :p
    print "Getting stock value"
    current_stock_value = nse.get_quote(stock_name)
    print current_stock_value["sellPrice1"]
    items_added, items_removed, items_modified, items_same = dict_compare(past_stock_value, current_stock_value)
    if items_modified:
       print "Stock value changed"
       toCsv(current_stock_value, stock_name)
       past_stock_value = copy.deepcopy(current_stock_value)
Esempio n. 39
0
from pprint import pprint
import json
from nsetools import Nse
nse = Nse()
q = nse.get_quote('infy') 
#pprint(q)
dict={}

dict['applicableMargin']=q['applicableMargin']
dict['averagePrice']=q['averagePrice']
dict['bcEndDate']=q['bcEndDate']
dict['bcStartDate']=q['bcStartDate']


print dict

Esempio n. 40
0
# test
nse = Nse()
print nse

all_stock_codes = nse.get_stock_codes()
ticklist = all_stock_codes.keys()
ticklist = sorted(ticklist)


while True:
    sata = pd.DataFrame()
    for ticker in ticklist:
        ptime = time.ctime()
        try:
            q = nse.get_quote(ticker)
            qdf = pd.DataFrame(q.items(), columns=["Item", "Value"])
            qdf["symbol"] = ticker
            qdf["timestamp"] = ptime
            # qdf = qdf.sort(['Item'])
            sata = pd.concat([sata, qdf], axis=0, ignore_index=True)
        except:
            continue
        sata.to_csv("nseOB11Nov2015.csv", index=False, mode="a")

data.sort(["symbol", "Item"], ascending=[False, True])

len(data.index) / 66


def get_quote(self, code, as_json=False):