Beispiel #1
0
	    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"
Beispiel #2
0
	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()
Beispiel #3
0
def addwatchlistitem(request):
    if request.method == "POST":
        # This is form class
        form = nse_f_addwatchlititem(request.POST)
        form.valid = True
        if form.is_valid():
            post = form.save(commit=False)
            post.stock_type = 'WL'
            #post.user = '******'
            #post.stamp = datetime.datetime.now()
            post.save()
        return redirect('Watch_List')
    else:
        form = nse_f_addwatchlititem()
        nse = Nse()
        all_stock_codes = nse.get_stock_codes()
        stock_list = all_stock_codes.items()
        return render(request, 'nse/addwatchlistitem.html', {
            'form': form,
            'stock_list': stock_list
        })
Beispiel #4
0
class Machine():
    def __init__(self):
        self.nse = Nse()

    def getQuote(self, stockName):
        """
		Fetches Quote for Given Stock
		"""
        return self.nse.get_quote(stockName)

    def showQuote(self, quote):
        """
		Pretty Print a received Quote
		"""
        pprint(quote)

    def getIndexList(self):
        """
		Fetches the available Index list
		"""
        return self.nse.get_index_list()

    def showIndexList(self):
        """
		Pretty Print available Index List
		"""
        pprint(self.getIndexList())

    def getIndexQuote(self, indexName):
        """
		Fetch Index Quote
		"""
        return self.nse.get_index_quote(indexName)

    def showIndexQuote(self, indexName):
        """
		Pretty Print Available Index Quote
		"""
        pprint(self.getIndexQuote(indexName))
Beispiel #5
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        entities = tracker.latest_message["entities"]
        nse = Nse()
        name = ""
        msg = ""
        for e in entities:
            if e["entity"] == "st_list":
                name = e["value"]

        q = nse.get_quote(name)
        msg = name.upper() + " Day High: " + str(
            q["dayHigh"]) + " Day Low: " + str(
                q["dayLow"]) + " Average Price: " + str(
                    q["averagePrice"]) + " Change: " + str(
                        q["change"]) + " Delivery Quantity " + str(
                            q["deliveryQuantity"]) + " pChange " + str(
                                q["pChange"])

        dispatcher.utter_message(msg)

        return []
Beispiel #6
0
def updateDatabaseCurrent(requests):
	(user,inputDict,getParams) = (request.user,request.data,request.GET)
	if user.userType not in [3, 4]:
		return errorResp(401)
	
	if 'update' not in inputDict:
		return errorResp(406)
	
	if not inputDict['update']:
		return Response({})

	nse = Nse()
	for symbol in COMPANIES:
		data = nse.get_quote(symbol)

		try:
			comp = company.objects.get(name = symbol)
		except:
			comp = company.objects.create(name = symbol)

		try:
			_=stockData.objects.get(companyDetails=comp,
							dataTime=data['secDate'])
		except:
			_=stockData.objects.create(companyDetails=comp,
							dateTime=data['secDate'],
							openPrice=data['open'],
							previousPrice=data['previousClose'],
							lowPrice=data['dayLow'],
							highPrice=data['dayHigh'],
							closePrice=data['closePrice'],
							# ltp=data['lastPrice'],
							# trades=data['totalTradedValue'],
							# turnover=data[''],
							volume=data['totalTradedVolume'],
							series=data['series'])

	return Response({'status': True, 'text': "Today's stockdata updated successfully." })
def get_market_data_for_stocks(stocks_list):
    nse = Nse()
    data = []
    for stock in stocks_list:
        print(stock)
        try:
            d1 = nse.get_quote(stock)
            print(d1)
        except Exception as e:
            print(e)
        if d1:
            data.append(list(d1.values()))
            columns = list(d1.keys())
        else:
            print('{} not found.'.format((stock)))
    df = pd.DataFrame(data, columns=columns)
    df= df[nse_config.nse_columns]
    df['pChange'] = df['pChange'].astype('float')
    df['low52'] = df['low52'].astype('float')
    df['high52'] = df['high52'].astype('float')
    df['closePrice'] = df['closePrice'].astype('float')


    df = df.sort_values('pChange', ascending=False)
    print('most increase changed stocks')
    print(df.head())
    print('most decrease changed stocks')
    print(df.tail())


    df['BELOW'] = ((df['high52'] - df['closePrice']) / df['closePrice']) * 100
    df = df.sort_values('BELOW', ascending=False)
    print('most below stocks from 52high')
    print(df.head())
    print('most above stocks to 52high')
    print(df.tail())
    return df
Beispiel #8
0
def detail(request, product_id):
    nse = Nse()
    top_gainers = nse.get_top_gainers()
    top_losers = nse.get_top_losers()

    response = requests.get(bseurl)
    bsedetail = response.json()
    response = requests.get(nseurl)
    nsedetail = response.json()
    response = requests.get(usdinrurl)
    usdinrdetail = response.json()
    response = requests.get(goldurl)
    golddetail = response.json()

    productcode = get_object_or_404(Product, pk=product_id)
    url = 'https://www.quandl.com/api/v3/datasets/AMFI/' + str(
        productcode.stockid) + '.json?api_key=a6QtRRy_axhp9mTMRvyC'
    url2 = 'https://www.quandl.com/api/v3/datasets/BSE/SENSEX.json?api_key=a6QtRRy_axhp9mTMRvyC'

    print(url)
    response = requests.get(url)
    stockdetail = response.json()
    return render(
        request, 'products/detail.html', {
            'stockdetail': stockdetail['dataset'],
            'topgainers': top_gainers_nse,
            'toplosers': top_losers_nse,
            'bsedetail': bsedetail,
            'nifty': nsedetail,
            'usdinrdetail': usdinrdetail,
            'golddetail': golddetail,
            'topgainersnse': top_gainers_nse,
            'toplosersnse': top_losers_nse,
            'topgainersbse': top_gainers_bse,
            'toplosersbse': top_losers_bse,
        })
Beispiel #9
0
def GetTopGainers():
    nse = Nse()
    values_list = [
        'open', 'dayHigh', 'dayLow', 'previousClose', 'lastPrice', 'change',
        'pChange', 'quantityTraded', 'totalTradedValue', 'high52', 'low52'
    ]
    a = [
        'ADANIPORTS', 'BPCL', 'COALINDIA', 'NTPC', 'SUNPHARMA', 'HINDALCO',
        'RELIANCE', 'TATASTEEL', 'GAIL', 'NESTLEIND', 'SBILIFE', 'GRASIM',
        'TCS', 'DIVISLAB', 'IOC', 'WIPRO', 'TATAMOTORS', 'ITC', 'TECHM',
        'HDFCLIFE', 'SBIN', 'ONGC', 'UPL', 'HCLTECH', 'M&M', 'JSWSTEEL',
        'POWERGRID', 'SHREECEM', 'LT', 'HDFCBANK', 'ULTRACEMCO', 'AXISBANK',
        'INDUSINDBK', 'HDFC', 'ASIANPAINT', 'CIPLA', 'TITAN', 'DRREDDY',
        'BAJAJFINSV', 'INFY', 'BAJAJ-AUTO', 'BRITANNIA', 'ICICIBANK',
        'KOTAKBANK', 'HINDUNILVR', 'BAJFINANCE', 'EICHERMOT', 'MARUTI',
        'HEROMOTOCO', 'BHARTIARTL'
    ]
    print(len(a))
    company_data = []
    start = time.time()
    for i in a:
        tempstart = time.time()
        result = nse.get_quote(i)
        temp = {}
        for itera in values_list:
            temp[itera] = result[itera]
        end = time.time()
        print(
            end - start,
            end - tempstart,
            i,
        )
        data = {}
        data[i] = temp
        company_data.append(data)
    return Response(json.dumps(company_data[2]), mimetype='application/json')
Beispiel #10
0
class Command(BaseCommand):
    def __init__(self):
        self.trending_company_repo = TrendingCompanyRepo()
        self.company_repo = CompanyRepo()
        self.nse = Nse()

    def run(self):
        gainers = self.nse.get_top_gainers()[:5]
        losers = self.nse.get_top_losers()[:5]
        print gainers, losers
        return
        g_comapnies = [
            self.company_repo.get_or_create(code=g['symbol']) for g in gainers
        ]
        l_comapnies = [
            self.company_repo.get_or_create(code=l['symbol']) for l in losers
        ]
        trendings = g_comapnies.extends(l_comapnies)
        date = helper.today()
        try:
            self.trending_company_repo.create(date=date, trendings=trendings)
        except Exception as e:
            print "error", e
        print "Done"
Beispiel #11
0
class Command(BaseCommand):
    def __init__(self):
        self.company_details_repo = CompanyDetailsRepo()
        self.company_repo = CompanyRepo()
        self.nse = Nse()
        self.stockapi = NSE()

    def run(self):
        nse_list = self.nse.get_stock_codes()

        for code, title in nse_list.iteritems():
            company = self.company_repo.filter(stockExchangeCode='NSE',
                                               code=code).first()
            if company:
                if company.weight < 1:
                    print "saving: ", code, title
                    company.weight += 1
                    company.save()
            else:
                print "creating: ", code, title
                try:
                    details = self.company_details_repo.create(**{})
                    c = self.company_repo.create(details=details,
                                                 **self._extract_company_data(
                                                     title, code))
                    c.details = details
                    c.save()
                    c = self.stockapi.latest(c)
                except:
                    print "error for " + title

    def _extract_company_data(self, name, code):
        return {
            "name": name,
            "code": code,
            #"quandlCode": data['dataset_code'],
            "description": name,
            "stockExchangeCode": 'NSE',
            "type": 'Time Series',
            "frequency": 'daily',
            "refreshedAt": helper.now(),
            #"oldestAvailableDate": helper.now(),
            "newAvailableDate": helper.now(),
            "history": [],
            "historyCount": 0,
            "weight": 1
        }
class nseClass:
    def __init__(self):
        from nsetools import Nse
        self.nse = Nse()

    def createStockCodeNameCSV(self):
        '''
            Creates a csv with 3 columns
            sl no, stock code name with stock name
        '''
        self.all_stocks = self.nse.get_stock_codes()
        import csv
        with open('nse_code_name.csv', 'w', newline='') as file:
            self.writer = csv.writer(file)
            self.writer.writerow(["SN", "Code", "Name"])
            for i, j in enumerate(self.all_stocks):
                if (i > 0):
                    self.writer.writerow([i, j, self.all_stocks[j]])
Beispiel #13
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()
Beispiel #14
0
class NseCommons(object):
    nse_obj = Nse()
    interval = 0

    def corn_job(self):
        try:
            while not FbObj.STOP_NSE_TOOL:
                try:
                    gainers = self.nse_obj.get_top_gainers()
                    for gainer in gainers:
                        if gainer.get("symbol") not in FbObj.TOP_MOVERS.keys():
                            FbObj.TOP_MOVERS[gainer.get("symbol")] = "None"
                    losers = self.nse_obj.get_top_losers()
                    for loser in losers:
                        if loser.get("symbol") not in FbObj.TOP_MOVERS.keys():
                            FbObj.TOP_MOVERS[loser.get("symbol")] = "None"
                    # logger.info(FbObj.TOP_MOVERS)
                    time.sleep(self.interval)
                    self.corn_job()
                except Exception as ex:
                    logger.error(ex)
                    logger.error(traceback.format_exc())
        except Exception as ex:
            logger.error(ex)
            logger.error(traceback.format_exc())

    def top_mover_thread(self, interval=60):
        try:
            logger.info("Trying to get top market movers")
            """ Constructor
            :type interval: int
            :param interval: Check interval, in seconds
            """
            self.interval = interval
            thread = threading.Thread(target=self.corn_job, args=())
            thread.daemon = True  # Daemonize thread
            thread.start()
            return thread
        except Exception as ex:
            logger.error(ex)
            logger.error(traceback.format_exc())
class Nsedata(object):
    def __init__(self):
        self.nse = Nse()
        self.data = self.nse.get_preopen_nifty(as_json=True)

    @property
    def get_gap_up_scrips(self):
        data = json.loads(self.data)  # load the json string into python list obj
        df = pd.DataFrame(data)       # Create data frame obj
        df['perChn'] = df['perChn'].astype(float)  # convert perChn value to float
        df = df[df['perChn'] > 1.0]                # filter out the scrips if perChn > 1
        df = df[df['iep'] < 500]
        return df[['symbol', 'iep', 'pCls', 'chn', 'perChn']]

    @property
    def get_gap_down_scrips(self):
        data = json.loads(self.data)  # load the json string into python list obj
        df = pd.DataFrame(data)       # Create data frame obj
        df['perChn'] = df['perChn'].astype(float)  # convert perChn value to float
        df = df[df['perChn'] < -1.0]                # filter out the scrips if perChn > 1
        df = df[df['iep'] < 500]
        return df[['symbol', 'iep', 'pCls', 'chn', 'perChn']]
Beispiel #16
0
class get_all_stock_codes:

    """
        This class will retrive all Stock codes from NSE website
    """

    def __init__(self):
        self.all_stock_codes = []
        self.nse = Nse()
        fileConfig('../properties/logging_config.ini')
        self.log = logging.getLogger()
        self.log.debug('Logger intiated ')

    def nsetools_get_codes(self, out_stock_file):
        """ This method retrivies all stock codes and write to CSV files
            Method uses NSETools to retrieve data from NSE website
        """
        self.log.info("Retriving stock Codes from NSE site .. ")
        self.all_stock_codes = self.nse.get_stock_codes()
        df2 = pd.DataFrame.from_dict(self.all_stock_codes, orient='index')
        self.log.info("Total Stock Codes received :" + str(df2.shape[0]))
        df2.to_csv(out_stock_file)
 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 ')
Beispiel #18
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

argnum = len(sys.argv)
scrip = str(sys.argv[1])

#logging.debug('A debug message!')
#logging.info('A debug message!')
#logging.critical('This is a critical message')

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

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

from nsetools import Nse
nse = Nse()

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

	T_UTC = datetime.utcnow()
	T_in  = T_UTC + timedelta(hours=5, minutes=30)
	quote_time =  T_in.strftime("%s");
	quotedata['timestamp'] = quote_time;
Beispiel #20
0
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 14 12:56:51 2015

@author: itithilien
"""

from nsetools import Nse
import pandas as pd
import time
from urllib2 import build_opener, HTTPCookieProcessor, Request

# 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'])
Beispiel #21
0
from nsetools import Nse
nse=Nse()
with open("/home/arya/Desktop/.stocks","r") as stocks:
    for stock in stocks:
        symbol=stock.strip()
        quote=nse.get_quote(symbol)
        price=quote["lastPrice"]
        average=quote["averagePrice"]
        dayLow=quote["dayLow"]
        dayHigh=quote["dayHigh"]
        low52=quote["low52"]
        high52=quote["high52"]
        change=quote["change"]
        close=quote["closePrice"]
        if close < 0:
            ch=False
        else:
            ch=True
        bg="^bg(#0F0)" if ch else "^bg($F00)"
        print(bg, symbol, price, change, average, dayLow, dayHigh, low52, high52, close, "^bg()")
        
Beispiel #22
0
# open the window
window.mainloop()

while 1:
    #for generation of delay
    import time

    # displaying the stock market data
    from nsetools import Nse

    # gettinfg the sports data
    import sports

    from win10toast import ToastNotifier

    nse = Nse()

    stocks = {
        "ADANIPORTS": 284.95,
        "HINDALCO": 152.30,
        "ONGC": 279.70,
        "SBIN": 259.70
    }

    qty = {
        "ADANIPORTS": 20,
        "HINDALCO": 20,
        "ONGC": 20,
        "SBIN": 20
    }
Beispiel #23
0
 def setUp(self):
     self.nse = Nse()
from nsepy import get_history
from datetime import date
from nsetools import Nse
nse = Nse()
import re

file = open("C:\\Users\\Ranjith\\Desktop\\NSE Scripts\\NSECodesList.txt", 'r')
OutputFile = open("C:\\Users\\Ranjith\\Desktop\\NSE Scripts\\NseHistory.txt", 'a+')
for line in file.readlines()[:1]:
        Code = re.sub("'","",line.split(':')[0])
        print (Code)
        data = get_history(symbol=Code, start=date(2017,11,1), end=date(2017,11,7))
        #OutputFile.write(Code+":"+str(data['Close'].to_dict())+"\n")
        print (data)


Beispiel #25
0
from nsetools import Nse
import json
import cx_Oracle
import sys
nse = Nse()
q = nse.get_quote(sys.argv[1])
parsed_json = json.loads(json.dumps(q))
v_open=parsed_json['open']
v_high=parsed_json['dayHigh']
v_low=parsed_json['dayLow']
v_quantitytraded=parsed_json['quantityTraded']
v_lastprice=parsed_json['lastPrice']
v_averageprice=parsed_json['averagePrice']
v_previousClose=parsed_json['previousClose']
con = cx_Oracle.connect('EQUITY/[email protected]/XE')
cur = con.cursor()
cur.callproc('DILLIP_FORMULA_PRC', (sys.argv[1],v_open,v_high,v_low,v_quantitytraded,v_lastprice,v_averageprice,v_previousClose))
cur.close()
Beispiel #26
0
#install these libraries - nsetools,pprint,csv
from nsetools import Nse
from pprint import pprint
from csv import writer

#function to insert things into csv
def append_list_as_row(file_name, list_of_elem):
# Open file in append mode
    with open(file_name, 'a+', newline='') as write_obj:
# Create a writer object from csv module
        csv_writer = writer(write_obj)
# Add contents of list as last row in the csv file
        csv_writer.writerow(list_of_elem)

nse= Nse()

#this list just stores names of the required stocks so that
#you can use this directly into your code and use accordingly
stocks_list = []

#top gainers
top_gainers = nse.get_top_gainers()

#remove comment of the next line to see all fields available
#pprint(top_gainers[0])

#insert column titles
row=['Stock name','Open price','High price','Low price','Previous price','Volume','Ltp']

#inserts the columns names into the csv file
append_list_as_row('topGainers.csv',row)
Beispiel #27
0
from nsetools import Nse
from pprint import pprint

nse = Nse()

symfile = open("symbolslist.txt")
q = nse.get_quote('infy')

varmar = q['varMargin']
varsym = q['symbol']
varh52 = q['high52']
varl52 = q['low52']
vardh = q['dayHigh']
vardl = q['dayLow']
varlstp = q['lastPrice']
varapm = q['applicableMargin']
varclp = q['closePrice']
varavp = q['averagePrice']

print "varMargin is" ,varsym
print varh52
print varl52
print vardh
print vardl
print varlstp
print varapm
print varclp
print varmar
print varavp
Beispiel #28
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
Beispiel #29
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))
Beispiel #30
0
from pytz import timezone
from datetime import datetime
from table_to_html import send_dataframe
from capital_allocation import cap_split_allocate, pick_stock

warnings.filterwarnings("ignore")

os.chdir("C:\\Users\\tomdx\\Documents\\GitHub\\stock")
ind_time = datetime.now(
    timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S.%f')

with open('nifty_100.pickle', 'rb') as handle:
    stock_dict = pickle.load(handle)

stocks_dict = {}
nse = Nse()

stock_parameters = ['dayHigh', 'dayLow', 'open', 'lastPrice', 'pChange']


@njit
def get_stock_data(nse=nse,
                   stock_parameters=stock_parameters,
                   stock_dict=stock_dict):

    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, [])
Beispiel #31
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)
Beispiel #32
0
from nsetools import  Nse
nse = Nse()
from pprint import pprint
indices = nse.get_index_list()
pprint(indices)
Beispiel #33
0
 def getStockSymbols(all):
     nse = Nse()
     all_stock_codes = nse.get_stock_codes()
     print(all_stock_codes)
Beispiel #34
0
from pprint import pprint
from nsetools import Nse
nse = Nse()
nifty_quote = nse.get_index_quote('cnx nifty')
pprint(nifty_quote)
Beispiel #35
0
from nsetools import Nse
nse = Nse()
q = nse.get_quote('infy')  # it's ok to use both upper or lower case for codes.
from pprint import pprint  # just for neatness of display
pprint(q)
Beispiel #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
        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))
Beispiel #37
0
 def setUp(self):
     self.nse = Nse()
Beispiel #38
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)
import os
import sys
from pprint import pprint  # just for neatness of display
from datetime import datetime
print('####################################################################',
      file=open("NSE_FnO_Todays_ Top_G_L.txt", "a"))
print('')  #,file=open("NSE_FnO_Todays_ Top_G_L.txt", "a"))
starttime = datetime.now().strftime(
    "%Y-%m-%d %H:%M:%S")  #program data pull start time

print('Start data pull for Stock Options from NSE server at time ',
      starttime,
      file=open("NSE_FnO_Todays_ Top_G_L.txt", "a"))

# Importing the NIFTY dataset from NSE live site / portel
nse = Nse()  # NSE object creation

day = datetime.now().strftime("%A")
daydate = datetime.now().strftime("%d")

if day == str('Thursday'):
    if int(daydate) >= 24:
        print(
            'Today is Monthly option expiry day : Carefully trade todays expiry day Call or Put options'
        )  #,file=open("NSE_FnO_Todays_ Top_G_L.txt", "a"))

####https://www.nseindia.com/json/option-chain/option-chain.json

#print (nse)

#Creating data frame for Option lotsize and there Rs. 1000 to Rs. 5000 price
Beispiel #40
0
    stock_codes_dataframe.to_csv('stock_codes.csv')

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)
 def __init__(self):
     self.nse = Nse()
Beispiel #42
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)
#imports
from nsetools import Nse
from datetime import datetime
import json
from pprint import pprint

#initializations
nse = Nse()
i = 0 

all_stock_codes = nse.get_stock_codes() #1626

with open('files/stock_data_min.json') as f :
    min_stock_data = json.load(f)
    # print(json.dumps(min_stock_data, indent=4, sort_keys=True))

# TODO: make this multithreaded
for stock_code in all_stock_codes : 
    try:
        stock_data = nse.get_quote(stock_code)
    except Exception as e:
        print(str(e), " for ", stock_code)
        continue
    today_date = datetime.today().strftime('%Y-%m-%d')

    data_for_today = {}
    data_for_today[today_date] = {
        "open": stock_data["open"],
        "high": stock_data["dayHigh"],
        "low" : stock_data["dayLow"],
        "close": stock_data["closePrice"]
Beispiel #44
0
from pprint import pprint
from nsetools import Nse
nse = Nse()
index_codes = nse.get_index_list()
pprint(index_codes)
Beispiel #45
0
from nsetools import Nse
import json
import cx_Oracle
import sys
nse = Nse()
q = nse.get_quote('L&TFH')
parsed_json = json.loads(json.dumps(q))
v_open = parsed_json['open']
v_high = parsed_json['dayHigh']
v_low = parsed_json['dayLow']
v_quantitytraded = parsed_json['quantityTraded']
v_lastprice = parsed_json['lastPrice']
v_averageprice = parsed_json['averagePrice']
v_previousClose = parsed_json['previousClose']
con = cx_Oracle.connect('EQUITY/[email protected]/XE')
cur = con.cursor()
cur.callproc('DILLIP_FORMULA_PRC',
             ('L&TFH', v_open, v_high, v_low, v_quantitytraded, v_lastprice,
              v_averageprice, v_previousClose))
cur.close()
Beispiel #46
0
from pprint import pprint
from nsetools import Nse
nse = Nse()
top_gainers = nse.get_top_gainers()
pprint(top_gainers)
top_losers = nse.get_top_losers()
pprint(top_losers)