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
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()
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))
def __init__(self, kafka_connection): self.nse = Nse() fileConfig('../properties/logging_config.ini') self.log = logging.getLogger() self.log.debug('stock_exit_strategy_simple intiated ') self._message_number_out = 0 self.connection = kafka_connection
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 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 })
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")
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)
def download_stock_data_method(**kwargs): nse = Nse() stock_names_dict = nse.get_stock_codes() stock_names_list = list(stock_names_dict.keys())[1:4] stocks = [] stocks = [ download_price_history_for_stock(symbol=stock) for stock in stock_names_list ] failed_stocks = [i for i in stocks if i] logging.info("Failed Stocks : ") logging.info(failed_stocks) failed_again = [] if len(failed_stocks) > 0: failed_again = [ download_price_history_for_stock(symbol=stock) for stock in failed_stocks ] if len(failed_again) > 0: logging.info("Failed STOCKS after multiple tries : ") logging.info(failed_again)
def __init__(self): self.nse = Nse() fileConfig('../properties/logging_config.ini') self.log = logging.getLogger() self.log.debug('Logger intiated ') #self.df = pd.DataFrame(columns=['SYMBOL','SERIES','OPEN','HIGH','LOW','CLOSE','LAST','PREVCLOSE','TOTTRDQTY','TOTTRDVAL','TIMESTAMP','TOTALTRADES','ISIN','unname']) self.df = pd.DataFrame()
def sharename(x): q = Nse().get_quote(x) mylist = list() mylist.append({'companyName': q['companyName']}) mylist.append({'symbol': q['symbol']}) mylist.append({'basePrice': q['basePrice']}) mylist.append({'closePrice': q['closePrice']}) mylist.append({'averagePrice': q['averagePrice']}) mylist.append({'open': q['open']}) mylist.append({'previousClose': q['previousClose']}) mylist.append({'dayHigh': q['dayHigh']}) mylist.append({'dayLow': q['dayLow']}) mylist.append({'high52': q['high52']}) mylist.append({'low52': q['low52']}) mylist.append({'pricebandupper': q['pricebandupper']}) mylist.append({'pricebandlower': q['pricebandlower']}) mylist.append({'totalBuyQuantity': q['totalBuyQuantity']}) mylist.append({'totalSellQuantity': q['totalSellQuantity']}) mylist.append({'totalTradedVolume': q['totalTradedVolume']}) mylist.append({'quantityTraded': q['quantityTraded']}) mylist.append({'deliveryQuantity': q['deliveryQuantity']}) mylist.append({'deliveryToTradedQuantity': q['deliveryToTradedQuantity']}) return (mylist)
def __init__(self, symbol): self.nse = Nse() self.symbol = symbol self.stocknamelist = [] self.closepricelist = [] self.yearhighlist = [] self.yearlowlist = []
def index(): nse = Nse() top_gainers = nse.get_top_gainers() top_losers = nse.get_top_losers() return render_template('marketcards.html', gainers=top_gainers, losers=top_losers)
def __init__(self): self.json_stock_realtime_quotes = [] self.nse = Nse() fileConfig('../properties/logging_config.ini') self.log = logging.getLogger() self.log.debug('Logger intiated ') self.temoutfile = open("D:\\stocks_temp_file3.txt", "a")
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)
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"})
class NSE: nse_obj = Nse() @classmethod def get_all_stock_codes(cls) -> list: return [{ 'stock_code': stock_code, 'companyName': companyName } for stock_code, companyName in cls.nse_obj.get_stock_codes().items()] @classmethod def get_stock_info(cls, stock_code) -> dict: stock_quote = cls.nse_obj.get_quote(stock_code) if stock_quote: return { 'companyName': stock_quote.get('companyName'), 'isinCode': stock_quote.get('isinCode'), 'symbol': stock_quote.get('symbol'), 'exchange': 'NSE', 'series': stock_quote.get('series') } else: return None @classmethod def get_stock_daily_price(cls, stock_code) -> dict: stock_quote = cls.nse_obj.get_quote(stock_code) return { 'secDate': stock_quote.get('secDate'), 'dayHigh': stock_quote.get('dayHigh'), 'dayLow': stock_quote.get('dayLow'), 'lastPrice': stock_quote.get('lastPrice'), 'open': stock_quote.get('open'), 'closePrice': stock_quote.get('closePrice') }
def alert_below_percentage(percentage): ''' :param percentage: how much lower the value has gone :return: list of StockInfo objects ''' logging.debug(f' Getting stocks below {percentage} %') result = [] # get live prices of VR stocks vr_live_prices = get_vr_price_live() #logging.debug(f'{vr_live_prices}') for stock in vr_live_prices[:]: #logging.debug(f'{stock.name}: {stock.pChange}') if abs(stock.pChange) > percentage: #print(stock.name) logging.debug(f'{stock.name}: {stock.pChange}') result.append(stock) logging.debug(f'VR results : {result}') # check 'NIFTY 50' nse = Nse() nifty_q = dict_to_stock_info(nse.get_index_quote(NIFTY)) #StockInfo = namedtuple('StockInfo', 'name symbol lastPrice pChange dayLow dayHigh open') if abs(nifty_q.pChange) > NIFTY_TRIGGER: logging.debug(f'Adding {nifty_q.name}: {nifty_q.pChange}') result.append(nifty_q) else: logging.debug(f'NIFTY change : {nifty_q.pChange}') return result
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))
def __init__(self): self.nse = Nse() fileConfig('../properties/logging_config.ini') self.log = logging.getLogger() self.log.debug('Logger intiated ') self.purchase_file = \ "D:\\nse_data\\purchase_details\\purchase_price_details.csv" self.output_file = "D:\\nse_data\\purchase_details\\output.csv"
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)
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')
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')
def nse_stock(self): nse = Nse() print("TOP GAINERS OF YESTERDAY") print(nse.get_top_gainers()) print( '-------------------------------------------------------------------------------------------------------' ) print("TOP LOSERS OF YESTERDAY") print(nse.get_top_losers())
def fetch_oi(expiry_dt): #**********Some Abbrivation********* #____PCR=PutCallRatio #____LTP=LastTradePrice #____Df=Dataframe #____TCVSP=TotalCashValue of Strike Price #****Creating empthy List to store the all these required data PCR = [] TIME= [] maxPain=[] StrikePriceList=[] while True: #Program will run continously r = session.get(url, headers=headers, timeout=15, cookies=cookies) r = r.json() nse=Nse() BankNiftyData = nse.get_index_quote("nifty bank") LTP=BankNiftyData.get('lastPrice') ce_values = [data['CE'] for data in r['records']['data'] if "CE" in data and data['expiryDate'] == expiry_dt] #Seperating All CE information from JsonData pe_values = [data['PE'] for data in r['records']['data'] if "PE" in data and data['expiryDate'] == expiry_dt] #Seperating All PE information from JsonData ce_dt = pd.DataFrame(ce_values).sort_values(['openInterest'],ascending=False) pe_dt = pd.DataFrame(pe_values).sort_values(['openInterest'],ascending=False) #***********Collecting All StrikePrice from Option Chain********* #StrikePriceDF=pd.DataFrame(ce_values) #StrikePriceList=StrikePriceDF['strikePrice'].values.tolist() #print(StrikePriceList) ce_dt[['strikePrice','lastPrice','openInterest', 'changeinOpenInterest']] Final_CE_Data=ce_dt[['strikePrice','lastPrice','openInterest', 'changeinOpenInterest']].iloc[:10] print("\n---------------------------------------") print("|*******printing OI CALL data***********|") print("---------------------------------------\n") print(Final_CE_Data) pe_dt[['strikePrice','lastPrice','openInterest', 'changeinOpenInterest']] Final_PE_Data=pe_dt[['strikePrice','lastPrice','openInterest', 'changeinOpenInterest']].iloc[:10] print("\n---------------------------------------") print("|*******printing OI PUT data***********|") print("---------------------------------------\n") print(Final_PE_Data) PCR_DataFrame,i=OI_PCR(ce_dt,pe_dt,TIME,PCR) #Calling to PCR calculation Fuction #print(PCR_DataFrame) ##----------------------------Max Pain Calculation----------------### ce_dt_MaxPain = pd.DataFrame(ce_values) pe_dt_MaxPain = pd.DataFrame(pe_values) MaxPain_Df=MaxPain(ce_dt_MaxPain,pe_dt_MaxPain,LTP) print(MaxPain_Df) ##----------------------------Chart Preparation For All Function ----------------## OI_Charts(Final_CE_Data,Final_PE_Data,PCR_DataFrame,MaxPain_Df)
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")
class Meta: model = trails fields = "__all__" nse = Nse() all_stock_codes = nse.get_stock_codes() trai = tuple((n, m) for n, m in all_stock_codes.items()) widgets = { 'stocks': forms.CheckboxSelectMultiple(choices=trai), }
class submod: nse = Nse() def domethod(): print("ran in sub mode" + submod.nse.get_quote_url) def domore(): submod.domethod()
def __init__(self, from_date, to_date=dt.datetime.now().date(), skip_dates=[]): """accepts date in fuzzy format""" self.bhavcopy_base_url = "https://www.nseindia.com/content/historical/EQUITIES/%s/%s/cm%s%s%sbhav.csv.zip" self.bhavcopy_base_filename = "cm%s%s%sbhav.csv" self.from_date = from_date self.to_date = to_date self.skip_dates = skip_dates self.nse = Nse() self.dates = self.generate_dates()
def __new__(cls, *args, **kwargs): if not NSEPyData.init_: import nsepy cls.nsepy = nsepy from nsetools import Nse cls.nse = Nse() NSEPyData.init_ = True instance = super(NSEPyData, cls).__new__(cls, *args, **kwargs) return instance