def index(request): b = BSE(update_codes=True) data_gainer_company = b.topGainers() data_looser_company = b.topLosers() company = [] for i in data_gainer_company: company.append(b.getQuote(i['scripCode'])) for i in data_looser_company: company.append(b.getQuote(i['scripCode'])) if (request.method == 'POST'): d = request.POST['search_items'] data = b.getQuote(d) search_items = True return render( request, 'index.html', { 'data_gainer_company': data_gainer_company, 'data_looser_company': data_looser_company, 'search_data': data, 'search_items': search_items }) else: main_page = True return render( request, 'index.html', { 'data_gainer_company': data_gainer_company, 'data_looser_company': data_looser_company, 'company': company, 'main_page': main_page })
def search_data(request, code): email = request.session['gmail'] details = users.objects.get(gmail=email) data = share_owner.objects.filter(user_gmail=email) dictionary_items = {} b = BSE() total_in_table = 0 total_in_actual = 0 for i in data: if (i.company_code in dictionary_items.keys()): dictionary_items[i.company_code][2] = dictionary_items[ i.company_code][2] + i.share_quntity else: dictionary_items[i.company_code] = [ i.company_code, i.company_name, i.share_quntity ] total_in_actual += float(b.getQuote( i.company_code)['currentValue']) * i.share_quntity total_in_table = total_in_table + i.total total_profit = int(total_in_actual - total_in_table) gmail = request.session['gmail'] data_owner = share_owner.objects.filter(user_gmail=gmail, company_code=code) for i in data_owner: i.date = str(i.date) return render( request, 'admin_Homepage.html', { 'details': details, 'data': dictionary_items, 'data_owner': data_owner, 'profit': total_profit })
class BSEDataStockMarketTalker(StockMarketTalker): MIN_TIME_BW_REQUESTS = 30 # So that we don't get banned by servers of BSE def __init__(self): super(BSEDataStockMarketTalker, self).__init__() self.bse = BSE() self.companyCodesToCompanyNamesMap = self.base.getScripCodes() assert (len(self.companyCodesTocompanyNamesMap) != 0) self.companyNamesToCompanyCodesMap = { value: key for key, value in self.companyCodesToCompanyNamesMap.items() } self.lastRequestTimestamp = time.time() def getStockInfo(self, stockName): ''' Returns complete information about a stock in a dictionary format ''' assert time.time( ) - self.lastRequestTimestamp > MIN_TIME_BW_REQUESTS, 'Please wait for {} seconds between subsequent server requests'.format( MIN_TIME_BW_REQUESTS) self.lastRequestTimestamp = time.time() stockCode = self._getStockCode(stockName) return self.bse.getQuote(stockCode) def getStockPrice(self, stockName): stockInfo = self.getStockInfo(stockName) return stockInfo['currentValue'] def _getStockCode(self, stockName): if stockName in self.companyCodesToCompanyNamesMap: return stockName assert stockName in self.companyNamesToCompanyCodesMap, 'Must supply either a valid company name or company code' return self.companyNamesToCompanyCodesMap[stockName]
def save_details(request, code): no_of_quntity = request.POST['no_of_quantity'] price = float(request.POST['price_of_share']) date = request.POST['select_date'] b = BSE() data = b.getQuote(code) comany_name = data['companyName'] total = int(int(no_of_quntity) * float(price)) company_data = { 'code': code, 'no_of_quntity': no_of_quntity, 'price': price, 'total': total } share_owner.objects.create(user_gmail=request.session['gmail'], date=date, company_code=code, company_name=comany_name, share_quntity=no_of_quntity, share_price=price, total=int(total)).save() return render(request, 'search_save.html', { 'search_data': data, 'company_data': company_data })
def sell_items(request, code): gamil = request.session['gmail'] sell_quantity = request.POST['sell_quentity'] sell_date = request.POST['sell_date'] sell_price = request.POST['sell_price'] data = share_owner.objects.filter(id=code) buy_price = data[0].share_price sell_profit = (int(sell_price) * int(sell_quantity)) - (int(buy_price) * int(sell_quantity)) total_sell = int(sell_quantity) * int(sell_price) sell_data_table.objects.create(user_gmail=gamil, company_code=data[0].company_code, company_name=data[0].company_name, buy_date=data[0].date, sell_date=sell_date, buy_price=data[0].share_price, sell_price=int(sell_price), total_sell_price=total_sell, total_profit=sell_profit, sell_quntity=int(sell_quantity)).save() if (data[0].share_quntity == int(sell_quantity)): share_owner.objects.filter(id=code).delete() else: ob = share_owner.objects.get(id=code) ob.share_quntity = ob.share_quntity - int(sell_quantity) ob.save() email = request.session['gmail'] details = users.objects.get(gmail=email) data = share_owner.objects.filter(user_gmail=email) b = BSE() total_in_table = 0 total_in_actual = 0 dictionary_items = {} for i in data: if (i.company_code in dictionary_items.keys()): dictionary_items[i.company_code][2] = dictionary_items[ i.company_code][2] + i.share_quntity else: dictionary_items[i.company_code] = [ i.company_code, i.company_name, i.share_quntity ] total_in_actual += float(b.getQuote( i.company_code)['currentValue']) * i.share_quntity total_in_table = total_in_table + i.total total_profit = int(total_in_actual - total_in_table) return render(request, 'admin_Homepage.html', { 'details': details, 'data': dictionary_items, 'profit': total_profit })
def getCurrentPrice(stockCode): # stockCode must be a code in String, eg. '500325' if(type(stockCode) != str): return 'Stock code should be a string' b = BSE(update_codes = True) try: stockDetails = b.getQuote(stockCode) return stockDetails['currentValue'] except AttributeError: return 'Not a valid stock code' #print(getCurrentPrice("500247"))
def main(): small_companies = [] b = BSE() df = pandas.read_csv(file_name) codes = df['Security Code'] # print(len(codes)) for code in codes: q = b.getQuote(str(code)) traded_value = q['totalTradedValue'] marketCapFull = q['marketCapFull'] marketCapFull_ = marketCapFull.split(" ")[0] traded_value_ = traded_value.split(" ")[0] if float(traded_value_) <= 0.99: small_companies.append(code) traded_value_int = Decimal(sub(r'[^\d.]', '', traded_value_)) * 10000000 market_cap_int = Decimal(sub(r'[^\d.]', '', marketCapFull_)) * 10000000 print( "{} | stock : {} | Traded Value {} | Market Capital {}".format( q['companyName'], q['currentValue'], traded_value_int, market_cap_int))
from bsedata.bse import BSE b = BSE() q = b.getQuote(str(532454)) print("company Name : {}".format(q['companyName'])) print("--------------------------------------------") print("current Value : {}".format(q['currentValue'])) print("52 week High : {}".format(q['52weekHigh'])) print("52 week Low : {}".format(q['52weekLow'])) print("totat Traded Value : {}".format(q['totalTradedValue'])) print("total Traded Quantity : {}".format(q['totalTradedQuantity']))
print(b) b = BSE(update_codes=True) while True: main_input = int( input( "\nWhat You Want To Do\nPress 1 to Get The List Of Todays Top Gainers\nPress 2 to Get The List Of Todays Top Losers\nPress 3 to Get The List of the Scrip Code Of The Respective Companies\nPress 4 to Get the Information About The Company Stock by Providing the Scrip Code: " )) scrip_code = b.getScripCodes() Gainers = b.topGainers() Losers = b.topLosers() if main_input == 1: print(json.dumps(Gainers, sort_keys=True, indent=4)) if main_input == 2: print(json.dumps(Losers, sort_keys=True, indent=4)) if main_input == 3: print(json.dumps(scrip_code, sort_keys=True, indent=4)) if main_input == 4: Quote = b.getQuote( input( "Please Enter The Scrip Code To Get The Information About The Company Stock: " )) print(json.dumps(Quote, sort_keys=True, indent=4)) con = int( input("\nDo You Want to Continue\nPress 1 For Yes\nPress 2 For No: ")) if con == 2: break
def user_login(request): if (request.method == 'POST'): try: first_name = request.POST['first_name_signup'] last_name = request.POST['last_name_signup'] email = request.POST['email_signup'] mobile = request.POST['mobile_signup'] password = request.POST['password_signup'] if (users.objects.filter(gmail=email)): sign_up_sucess = False email_already = True login_problem = False return render( request, 'user_login.html', { 'sign_up_sucess': sign_up_sucess, 'email_already': email_already, 'login_problem': login_problem }) else: users.objects.create(user_first_name=first_name, user_last_name=last_name, password=password, mobile=mobile, gmail=email).save() sign_up_sucess = True email_already = False login_problem = False return render( request, 'user_login.html', { 'sign_up_sucess': sign_up_sucess, 'email_already': email_already, 'login_problem': login_problem }) except: email = request.POST["email_login"] password = request.POST["password_login"] u = users.objects.filter(gmail=email, password=password) if (len(u) > 0): request.session['gmail'] = email details = users.objects.get(gmail=email) data = share_owner.objects.filter(user_gmail=email) dictionary_items = {} b = BSE() total_in_table = 0 total_in_actual = 0 for i in data: if (i.company_code in dictionary_items.keys()): dictionary_items[i.company_code][2] = dictionary_items[ i.company_code][2] + i.share_quntity else: dictionary_items[i.company_code] = [ i.company_code, i.company_name, i.share_quntity ] total_in_actual += float( b.getQuote( i.company_code)['currentValue']) * i.share_quntity total_in_table = total_in_table + i.total total_profit = int(total_in_actual - total_in_table) return render( request, 'admin_Homepage.html', { 'details': details, 'data': dictionary_items, 'profit': total_profit }) else: sign_up_sucess = False email_already = False login_problem = True return render( request, 'user_login.html', { 'sign_up_sucess': sign_up_sucess, 'email_already': email_already, 'login_problem': login_problem }) else: sign_up_sucess = False email_already = False login_problem = False return render( request, 'user_login.html', { 'sign_up_sucess': sign_up_sucess, 'email_already': email_already, 'login_problem': login_problem })
def handle_data(): comp = request.form['tags'] print(comp) b = BSE() b.updateScripCodes() d = b.getScripCodes() rev_d = dict(map(reversed, d.items())) scripcode = rev_d[comp] print(scripcode) quote = b.getQuote(scripcode) company = quote["securityID"] print(company) # -----------READING NSE DATA url = 'https://www.nseindia.com/api/chart-databyindex?index=' + company + 'EQN' headers = { 'referer': 'https://www.nseindia.com/get-quotes/equity?symbol=' + company, 'Content-Type': 'application/json; charset=utf-8', 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.113 Safari/537.36', 'x-requested-with': 'XMLHttpRequest' } nse = requests.get(url, headers=headers) nse_text = nse.text nsedata = json.loads(nse_text) #print(type(nsedata["grapthData"])) l = nsedata["grapthData"] #-------------- READ NSE DATA , NOW BSE DATA bse_url = 'https://api.bseindia.com/BseIndiaAPI/api/StockReachGraph/w?scripcode=' + str( scripcode) + '&flag=0&fromdate=&todate=&seriesid=' bse = requests.get(bse_url) bse_text = bse.text bse_data = json.loads(bse_text) #print(type(bsedata)) #------------ READ BSE DATA dat = bse_data["Data"] dat_dict = json.loads(dat) bse_final_list = [] bse_temp_list = [] for i in dat_dict: #print(i['dttm']) date_obj = datetime.strptime(i['dttm'], '%a %b %d %Y %H:%M:%S') ms = date_obj.timestamp() * 1000 ms = int(ms) + 19800000 bse_temp_list.append(ms) bse_temp_list.append(i['dttm']) bse_temp_list.append(float(i['vale1'])) bse_final_list.append(bse_temp_list) bse_temp_list = [] ''' print("------------------------------------") print(len(bse_final_list)) print(len(l)) ''' pprint(l) print("-------------------------") pprint(bse_final_list) labels = [] values = [] diff_final_list = [] diff_temp_list = [] for j in bse_final_list: for k in l: if j[0] == k[0]: ts = int(j[0]) / 1000 print( datetime.utcfromtimestamp(ts).strftime( '%Y-%m-%d %H:%M:%S')) diff_temp_list.append(j[0]) diff = abs(float(j[2]) - float(k[1])) labels.append(j[0]) values.append(round(diff, 2)) diff_temp_list.append(round(diff, 2)) diff_final_list.append(diff_temp_list) diff_temp_list = [] pprint(diff_final_list) print(labels) print(values) return render_template('graph.html', labels=labels, values=values, name=comp, scode=scripcode, ccode=company)
def get_bse_stock_quotes(): bse_stock = BSE() bse_quote = bse_stock.getQuote(TCS) return bse_quote
from bsedata.bse import BSE import urllib.request b = BSE() print(b) # Output: # Driver Class for Bombay Stock Exchange (BSE) # to execute "updateScripCodes" on instantiation b = BSE(update_codes = True) q = b.getQuote('534976') print(q) contents = urllib.request.urlopen("https://www.bseindia.com/stock-share-price/reliance-industries-ltd/reliance/500325/") print(contents)
df['BSE Scrip'] = df['BSE Scrip'].astype(int) df['BSE Scrip'] = df['BSE Scrip'].astype(str) def LiveMarket(): conditions = True for ticker in df['BSE Scrip']: print("Scraping BSE Website for Live prices") LiveStock[ticker] = list(b.getQuote(ticker)) HUL = b.getQuote('500696') print(HUL) HUL_df = pd.DataFrame.from_dict(HUL,orient = 'index') HUL_df '''buy_orders = pd.DataFrame.from_dict(HUL['buy'],orient='index') buy_orders.columns = ['buyPrice','buyQty'] sell_orders = pd.DataFrame.from_dict(HUL['sell'],orient='index') sell_orders.columns = ['SellPrice','SellQty'] HUL_orderbook = buy_orders.append(sell_orders) frame = [buy_orders,sell_orders]
# '500875': 'Itc Ltd.' #storing the stocks to be tracked in my_stocks list my_stocks = [] for s in codelist: t = stock(s) #create a stock object for each company my_stocks.append(t) #following code runs all the time while True: time.sleep( 3600 ) #after every one hour it fetches the details of the my_stock prices and checks if target or stoploss is hit try: for st in my_stocks: t = b.getQuote(st.code) current_price = float(t["currentValue"]) if current_price >= sell_price: notify("sell", st.name, current_price) elif current_price <= buy_price: notify("buy", st.name, current_price) except Exception as e: print("Error occured: Below are the details") print(e) def notify(notification_type, name, code): if notification_type == sell: message = "Hi ! Congratulations. Its selling time. the price of share of " + name + " has reached the target price." else:
import json from conf import constants as const from classes import OLHBasicClass from datetime import datetime, date, timedelta from pprint import pprint nse = Nse() bse = BSE() ol_stocks = dict() oh_stocks = dict() for nse_stk, bse_stk in const.NSE_BSE_SYMBOLS.items(): print("# Processing {}".format(nse_stk)) bse_quote = bse.getQuote(bse_stk) bse_data = OLHBasicClass.OLHBasicClass( nse_stk, date.today(), bse_quote.get('previousOpen'), bse_quote.get('dayHigh'), bse_quote.get('dayLow'), bse_quote.get('currentValue'), bse_quote.get('totalTradedQuantity'), bse_quote.get('weightedAvgPrice'), bse_quote.get('previousClose'), 'BSE') if bse_quote.get('previousOpen') == bse_quote.get('dayLow'): if nse_stk in ol_stocks: ol_stocks[nse_stk].append(bse_data) else: ol_stocks[nse_stk] = [ bse_data, ] print(bse_data)
def search_save(request): search_items = request.POST['search_items'] print(search_items) b = BSE() search_data = b.getQuote(search_items) return render(request, 'search_save.html', {'search_data': search_data})
from bsedata.bse import BSE from time import sleep from win10toast import ToastNotifier hr = ToastNotifier() b = BSE() scriptCode = input("Enter company script code: ") cp = int(input("Enter cost price: ")) lowerBound = int(input("Enter give up price: ")) upperBound = int(input("Enter notifier price: ")) while True: data = b.getQuote(scriptCode) price = data["currentValue"] print(price) if (price < lowerBound): print("Sell now") elif (price > lowerBound and price > cp and price < upperBound): print("Profittt") elif (price >= upperBound): print("Target hit, current price is", price) hr.show_toast("Target hit, current price is", str(price)) sleep(2)
from bsedata.bse import BSE from pprint import pprint # just for neatness of display b = BSE() # print(b) q = b.getQuote("500209") pprint(q)