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 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 })
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 start(): flag = request.args.get("id") from bsedata.bse import BSE b = BSE() b = BSE(update_codes=True) def getBSEData(s): q = b.getQuote(s) print(q) return q return getBSEData(flag)
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"))
class BSE: bse_obj = BSE() @classmethod def get_stock_info(cls, stock_code) -> dict: stock_quote = cls.bse_obj.getQuote(stock_code) return stock_quote
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 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 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 import json b = BSE() 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: "))
from flask import Flask,request,jsonify,url_for,render_template,redirect,logging import json import pandas as pd import csv import datetime import subprocess from bsedata.bse import BSE from csv import DictWriter from forms import inputOrderForm from Matching import matching from Cancellation import remove from flask_apscheduler import APScheduler from apscheduler.schedulers.background import BackgroundScheduler b=BSE() b.updateScripCodes() data = {} with open('./stk.json', 'r') as f: data = json.load(f) with open('static/stk.json', 'w') as f: json.dump(data, f) app = Flask(__name__) scheduler = APScheduler() scheduler.init_app(app) scheduler.start() scheduler.add_job(id="remove" ,func = remove, trigger = 'cron',day_of_week='mon-sun',hour=15,minute=30) scheduler.add_job(id="matching" ,func = matching, trigger = 'cron', day_of_week='mon-sun',hour=9,minute=15) app.config['SECRET_KEY'] = 'secret' day = datetime.datetime.now().strftime("%w")
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)
def get_bse_stock_quotes(): bse_stock = BSE() bse_quote = bse_stock.getQuote(TCS) return bse_quote
from bsedata.bse import BSE b=BSE() def index(req): postData = req.form code = str(postData['param'].value) b.updateScripCodes() result=b.verifyScripCode(code) # print(result) return result
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)
from bsedata.bse import BSE b = BSE() import pandas as pd print(b) # Output: # Driver Class for Bombay Stock Exchange (BSE) import time import multiprocessing # to execute "updateScripCodes" on instantiation b = BSE(update_codes = True) df = pd.read_csv("StockDataFetchScrips - Sheet1.csv") df.columns df = df.drop(df.index[0]) df.head() 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))
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)
import smtplib import time from bsedata.bse import BSE b = BSE() b = BSE(update_codes=True) # codes of stocks to be tracked are stored in codelist codelist = [ '500570', '500400', '532540', '500770', '500470', '512599', '532921', '533096', '539254', '500820', '532977', '532281', '500180', '507685', '500875' ] profit_percent = 0.40 stoploss_percent = 0.30 # for every company we will create a stock initialized with following attributes class stock: def __init__(self, code): st = b.getQuote(code) self.name = st["companyName"] self.code = code current_price = float(st["currentValue"]) self.sell_price = current_price + profit_percent * current_price self.buy_price = current_price - stoploss_percent * current_price # codes of some of the companies # '500570': 'Tata Motors Ltd.'
from bsedata.bse import BSE from newsapi import NewsApiClient as nac s = BSE() n = nac(api_key="ec672e47cdcd409db8dc987e04aa7251") def stock(): try: print("Tata Steel and BSE SENSEX values:\n") quote = s.getQuote("500055") #tata steel print("Tata Steel (500055):") print("\tOpen:", quote["previousOpen"]) print("\tClose:", quote["previousClose"]) print("\tHigh:", quote["dayHigh"]) print("\tLow:", quote["dayLow"]) print( "\nBSE SENSEX value:", s.getIndices( category='market_cap/broad')['indices'][0]["currentValue"]) except IndexError as ier: print( "Failed to retrieve BSE SENSEX/TATA STEEL PVT LTD data, try after sometime.\nKeep the interval between requests greater than 5 sec" ) print("\n\n") def news(): print("\n\nTop 5 News Headlines:\n") news = n.get_top_headlines(language="en", country="in") for article in news['articles'][:5]:
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']))
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})
import sys from bsedata.bse import BSE import pandas as pd import pprint b = BSE() b.updateScripCodes() #store the scripts codes in BseScripCodes.txt print(b.getScripCodes(), file=open('BseScripCodes.txt', 'wt')) #convert scripts codes from BseScripCodes.txt to BseScripCodes.xlsx df = pd.DataFrame(data=b.getScripCodes(), index=[0]) df = (df.T) df.to_excel('BseScripCodes.xlsx')
from bsedata.bse import BSE b = BSE() data = b.getScripCodes() # print(data) # value = b.getQuote("507685") # # print(value) # data1 = b.getQuote("532540") # print(data1) tg = b.topGainers() # print(tg) tl = b.topLosers() # print(tl) test = b.verifyScripCode("5325402") print(test)
from nsetools import Nse from bsedata.bse import BSE 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] = [
from bsedata.bse import BSE from pprint import pprint # just for neatness of display b = BSE() # print(b) q = b.getQuote("500209") pprint(q)
from rest_framework.response import Response from nsetools import Nse from pprint import pprint # just for neatness of display from datetime import datetime, timedelta import pandas as pd import io from bsedata.bse import BSE import requests from django import template defaultfundprice = 0 search_term = '' nse = Nse() top_gainers_nse = nse.get_top_gainers() top_losers_nse = nse.get_top_losers() bse = BSE() top_gainers_bse = bse.topGainers() top_losers_bse = bse.topLosers() ##moneycontrol appfeeds bseurl = 'http://appfeeds.moneycontrol.com/jsonapi/market/indices&ind_id=4' nseurl = 'http://appfeeds.moneycontrol.com/jsonapi/market/indices&ind_id=9' usdinrurl = 'https://priceapi.moneycontrol.com/pricefeed/notapplicable/currencyspot/%24%24%3BUSDINR' goldurl = 'https://priceapi.moneycontrol.com/pricefeed/mcx/commodityfuture/GOLD?expiry=05FEB2020' # Create your views here. def getPageData(request, allFundList): page = request.GET.get('page', 1) paginator = Paginator(allFundList, 30)
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 })
copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import pytest from bsedata.bse import BSE b = BSE(update_codes=True) @pytest.mark.parametrize("scripCode", ['534976', '500116', '512573']) def test_getQuote_valid(scripCode): assert len(b.getQuote(scripCode)) == 27 def test_getQuote_invalid(): with pytest.raises(AttributeError): assert b.getQuote('513715') def test_verifyCode_valid(): assert b.verifyScripCode('534976') == 'V-mart Retail Ltd.'
def main(): b = BSE() # b = b.getScripCodes() indices = b.getIndices(category='market_cap/broad') pprint(indices)