コード例 #1
0
def home(request):
    nse = Nse()
    nifty_bank = nse.get_index_quote("nifty bank")
    nifty_50 = nse.get_index_quote("nifty 50")
    india_vix = nse.get_index_quote("india vix")
    contaxt = {
        'nifty_bank': nifty_bank,
        'nifty_50': nifty_50,
        'india_vix': india_vix
    }
    return render(request, 'stockinfo/base.html', contaxt)
コード例 #2
0
    def download_stock_data_for_analysis(stock01, stock02, start_date,
                                         end_date, is_stock01_index,
                                         is_stock02_index):
        nse = Nse()
        path_local = '../data/pairTradeData/'
        path_heroku = '/app/data/pairTradeData/'
        file_01 = path_local if os.path.isdir(path_local) else path_heroku

        file = file_01 + stock01.replace(" ", "") + '_' + stock02.replace(
            " ", "") + '.csv'

        history_stock01 = get_history(symbol=stock01,
                                      start=start_date,
                                      end=end_date,
                                      index=is_stock01_index)
        history_stock02 = get_history(symbol=stock02,
                                      start=start_date,
                                      end=end_date,
                                      index=is_stock02_index)
        if len(history_stock01.index) != len(history_stock02.index):
            print("Size " + stock01 + " = " + str(len(history_stock01.index)))
            print("Size " + stock02 + " = " + str(len(history_stock02.index)))
            print(
                " ******************** Data size(No Of Rows) is not same: So exiting the program  ******************** "
            )
            sys.exit()

        close_price_history_stock01 = history_stock01[['Close']]
        close_price_history_stock02 = history_stock02[['Close']]

        merged_data = pd.concat(
            [close_price_history_stock01, close_price_history_stock02], axis=1)
        merged_data.to_csv(file, index=True, header=[stock01, stock02])

        if (is_stock01_index == False):
            ltp_stock01 = PairDataAnalysis.get_ltp(stock01)
        else:
            quote_01 = nse.get_index_quote(stock01)
            ltp_stock01 = quote_01['lastPrice']

        if (is_stock02_index == False):
            ltp_stock02 = PairDataAnalysis.get_ltp(stock02)
        else:
            quote_02 = nse.get_index_quote(stock02)
            ltp_stock02 = quote_02['lastPrice']

        ltp_content_to_write = datetime.today().strftime(
            '%Y-%m-%d') + "," + str(ltp_stock01) + "," + str(ltp_stock02)
        write(file, ltp_content_to_write)
コード例 #3
0
def alert_below_percentage(percentage):
    '''
    :param percentage: how much lower the value has gone
    :return: list of StockInfo objects
    '''
    logging.debug(f' Getting stocks below {percentage} %')
    result = []
    # get live prices of VR stocks
    vr_live_prices = get_vr_price_live()
    #logging.debug(f'{vr_live_prices}')
    for stock in vr_live_prices[:]:
        #logging.debug(f'{stock.name}: {stock.pChange}')
        if abs(stock.pChange) > percentage:
            #print(stock.name)
            logging.debug(f'{stock.name}: {stock.pChange}')
            result.append(stock)
    logging.debug(f'VR results : {result}')

    # check 'NIFTY 50'
    nse = Nse()
    nifty_q = dict_to_stock_info(nse.get_index_quote(NIFTY))
    #StockInfo = namedtuple('StockInfo', 'name symbol lastPrice pChange dayLow dayHigh open')
    if abs(nifty_q.pChange) > NIFTY_TRIGGER:
        logging.debug(f'Adding {nifty_q.name}: {nifty_q.pChange}')
        result.append(nifty_q)
    else:
        logging.debug(f'NIFTY change : {nifty_q.pChange}')

    return result
コード例 #4
0
def fetch_oi(expiry_dt):
   #**********Some Abbrivation*********
   #____PCR=PutCallRatio
   #____LTP=LastTradePrice
   #____Df=Dataframe
   #____TCVSP=TotalCashValue of Strike Price
   #****Creating empthy List to store the all these required data 
   PCR = []
   TIME= []
   maxPain=[]
   StrikePriceList=[]
   
   while True:                              #Program will run continously
       r = session.get(url, headers=headers, timeout=15, cookies=cookies)
       r = r.json()
       
       nse=Nse()
       BankNiftyData = nse.get_index_quote("nifty bank")
       LTP=BankNiftyData.get('lastPrice')
       
       ce_values = [data['CE'] for data in r['records']['data'] if "CE" in data and data['expiryDate'] == expiry_dt] #Seperating All CE information from JsonData
       pe_values = [data['PE'] for data in r['records']['data'] if "PE" in data and data['expiryDate'] == expiry_dt] #Seperating All PE information from JsonData

       ce_dt = pd.DataFrame(ce_values).sort_values(['openInterest'],ascending=False)
       pe_dt = pd.DataFrame(pe_values).sort_values(['openInterest'],ascending=False)
       #***********Collecting All StrikePrice from Option Chain*********
       #StrikePriceDF=pd.DataFrame(ce_values)
       #StrikePriceList=StrikePriceDF['strikePrice'].values.tolist()
       #print(StrikePriceList)
       
       ce_dt[['strikePrice','lastPrice','openInterest', 'changeinOpenInterest']]
       Final_CE_Data=ce_dt[['strikePrice','lastPrice','openInterest', 'changeinOpenInterest']].iloc[:10]
       print("\n---------------------------------------")
       print("|*******printing OI CALL data***********|")
       print("---------------------------------------\n")
       print(Final_CE_Data)
   
       pe_dt[['strikePrice','lastPrice','openInterest', 'changeinOpenInterest']]
       Final_PE_Data=pe_dt[['strikePrice','lastPrice','openInterest', 'changeinOpenInterest']].iloc[:10]
   
       print("\n---------------------------------------")
       print("|*******printing OI PUT data***********|")
       print("---------------------------------------\n")
       print(Final_PE_Data)
       
       PCR_DataFrame,i=OI_PCR(ce_dt,pe_dt,TIME,PCR)    #Calling to PCR calculation Fuction 
       
       #print(PCR_DataFrame)
      
##----------------------------Max Pain Calculation----------------###
       ce_dt_MaxPain = pd.DataFrame(ce_values)
       pe_dt_MaxPain = pd.DataFrame(pe_values)
       MaxPain_Df=MaxPain(ce_dt_MaxPain,pe_dt_MaxPain,LTP)
       print(MaxPain_Df)
     
##----------------------------Chart Preparation For All Function ----------------##
       OI_Charts(Final_CE_Data,Final_PE_Data,PCR_DataFrame,MaxPain_Df)
コード例 #5
0
def basic():
    nse = Nse()
    cmp = nse.get_index_quote('NIFTY BANK')
    cmp = cmp['lastPrice']
    cmp = int(round(cmp / 100.0) * 100.0)
    l = []

    new_url = 'https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY'
    headers = {'User-Agent': 'Mozilla/5.0'}

    page = requests.get(new_url, headers=headers)
    while len(page.content) == 272:
        page = requests.get(new_url, headers=headers)
        print("Fetching data... Please wait")
    dajs = page.json()
    l.append(dajs)
    l.append(cmp)
    return l
コード例 #6
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))
コード例 #7
0
    if main_input == 1:
        print(json.dumps(top_gainers, sort_keys=True, indent=4))

    if main_input == 2:
        print(json.dumps(top_losers, sort_keys=True, indent=4))

    if main_input == 3:
        x = int(
            input(
                "\nWhich Type Of Index Quote You Want To See\nPress 1 to get the List Of Index Quote\nPress 2 to Search The Index Quote: "
            ))
        if x == 1:
            print(json.dumps(index_quote_list, sort_keys=True, indent=4))

        if x == 2:
            index_quote_search = nse.get_index_quote(
                input("Search A Index Quote: "))
            print(json.dumps(index_quote_search, sort_keys=True, indent=4))

    if main_input == 4:
        Quote = nse.get_quote(
            input(
                "\nPlease Enter The Stock Symbol (For Example: Infosys Technologies = 'infy') To Get The Information About The Company Stock: "
            ))
        print(json.dumps(Quote, sort_keys=True, indent=4))

    if main_input == 5:
        print(json.dumps(all_stock_codes, sort_keys=True, indent=4))

    if main_input == 6:
        print(json.dumps(adv_dec, sort_keys=True, indent=4))
コード例 #8
0
ファイル: views.py プロジェクト: lksh2812/herodha
es = Elasticsearch(ELASTICSEARCH_URL)

from nsetools import Nse
nse = Nse()

from .forms import CustomUserCreationForm

from .checksum import *

from django.conf import settings
from django.core.cache.backends.base import DEFAULT_TIMEOUT
from django.views.decorators.cache import cache_page
CACHE_TTL = getattr(settings, 'CACHE_TTL', DEFAULT_TIMEOUT)

#Market Action
nifty_50 = nse.get_index_quote('nifty 50')
nifty_bank = nse.get_index_quote('nifty bank')
nifty_pharma = nse.get_index_quote('nifty pharma')
nifty_it = nse.get_index_quote('nifty it')
nifty_auto = nse.get_index_quote('nifty auto')

#Top Gainers
top_gainers = nse.get_top_gainers()

#Top Losers
top_losers = nse.get_top_losers()

# Create your views here.
# from .forms import RegistrationForm
# from django.contrib.auth.models import User
コード例 #9
0
ファイル: nse_tests.py プロジェクト: videetssinghai/nsetools
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)
コード例 #10
0
EMAMI --  900 50K   (< 950)
'''
'''
q1 = nse.get_stock_codes()
pprint(q1)

index_codes = nse.get_index_list()
pprint(index_codes)

quote = nse.get_index_quote('NIFTY 50')
pprint(quote)


'''

quote = nse.get_index_quote('NIFTY 50')
pprint(quote)

print('%10s%8s%8s%8s%8s%8s%8s%8s%8s%8s%8s%8s' %
      ('Name', 'Price', 'Pclose', 'Open', 'DHigh', 'DLow', '52High', '52Low',
       'FV', 'Target', 'Action', 'Diff'))

for stk in stks:
    print stk
    '''    
    try:
        q = nse.get_quote(stk)
    except Exception,e:
        print e
        continue
    '''
コード例 #11
0
import pandas as pd
import math
from datetime import datetime
from nsetools import Nse

# Importing the NIFTY dataset from NSE live site / portel

nse = Nse()  # NSE object creation
print('AI Result Start Time')
print('Main Program')
print('', file=open("NSEmarket.txt", "a"))
print('')

# Capital letter words / variable which are not appre in data variable box to reduce the display data frames and clean program view

Nf_n50 = nse.get_index_quote("nifty 50")

N50 = Nf_n50['lastPrice']
#N50 = 11000 # Sample test data
N50p = int(50 * round(float(N50) / 50))
n50f = format(N50p, '.2f')

BN_bank = nse.get_index_quote("nifty bank")
#BN = 22000 # Sample test data
BN = BN_bank['lastPrice']
BNp = int(50 * round(float(BN) / 50))
bnf = format(BNp, '.2f')

# Importing the Option dataset from Files stored in same folder
## Run the specific files on 9:45  12 and 1:30 each day and save on exit
コード例 #12
0
    ticker = j.strip()
    progress(n, total, status=ticker)
    quote = nse.get_quote(ticker)
    data = {
        "open": float(quote["open"]) if quote["open"] else 0.0,
        "close": float(quote["closePrice"]) if quote["closePrice"] else 0.0,
        "pChange": float(quote["pChange"]) if quote["pChange"] else 0.0,
        "date": curr,
    }
    nifty500_data[ticker] = data
    n += 1
    # db.collection(ticker).document(curr).set(data)
print()

# Get Index quote
quote = nse.get_index_quote("NIFTY 500")
nifty500_quote = {
    "lastPrice": float(quote["lastPrice"]) if quote["lastPrice"] else 0.0,
    "change": float(quote["change"]) if quote["change"] else 0.0,
    "pChange": float(quote["pChange"]) if quote["pChange"] else 0.0,
    "date": curr,
}
# Update index quote in database
db.collection("NIFTY500").document(curr).set(nifty500_quote)

# Sort the data by pChange
sorted_p = sorted(nifty500_data.items(), key=lambda x: x[1]["pChange"], reverse=True)
content = "Today's Max Gainers\n"
content += "NIFTY 500: " + str(nifty500_quote["pChange"]) + "\n\n"
for i in sorted_p[:20]:
    content += i[0] + ": " + str(i[1]["pChange"]) + "\n"
コード例 #13
0
df_info['open']=q['open']
df_info['dayHigh']=q['dayHigh']
df_info['dayLow']=q['dayLow']
df_info['close']= q['closePrice']
"""


nse.is_valid_code('infy') # this should return True True
nse.is_valid_code('innnfy') # should return False False

nse.is_valid_index('cnx nifty') # should return True True
nse.is_valid_index('cnxnifty') # should return False False


nse.get_index_list()
nse.get_index_quote("nifty bank")
all_stock_codes = nse.get_stock_codes()
df_stock_codes=pd.DataFrame(all_stock_codes.items(), columns=['SYMBOL', 'NAME OF COMPANY'])

index_codes = nse.get_index_list()
pprint(index_codes)
df_index_codes=pd.DataFrame(index_codes)

adv_dec = nse.get_advances_declines()
pprint(adv_dec)

top_gainers = nse.get_top_gainers()
df_topgainers=pd.DataFrame(top_gainers)
df_topgainers_info=df_topgainers.loc[:,['symbol','openPrice','highPrice','ltp']]

top_losers = nse.get_top_losers()
コード例 #14
0
ファイル: nse_getprice.py プロジェクト: SidharthArya/.bspwm
import sys
from nsetools import Nse
nse = Nse()
INDEX = sys.argv[1]
#print(INDEX)
print(nse.get_index_quote(INDEX)["lastPrice"])
コード例 #15
0
#!/usr/bin/env python
# coding: utf-8

from nsetools import Nse
from nsepy import get_history, get_quote
from datetime import date
import pandas as pd
#use pandas package to create dataframe object from the json object
from pandas.io.json import json_normalize
import numpy as np
nse = Nse()

# to get the quotation infor of stocks 
nse.get_index_quote("nifty midcap 150")

# get all stocks codes and the company name traded on NSE
all_stock_codes = nse.get_stock_codes(cached=False)

# get the list of codes of all the traded indices with return type as list
index_codes = nse.get_index_list()
# pprint(index_codes)

"""
Advances Declines an important feature which, in a brief snapshot, tells the story of trading day for the given index.
It contains the numbers of rising stocks, falling stocks and unchanged stock in a given trading day, per index.
"""
adv_dec = nse.get_advances_declines()
#pprint(adv_dec)

top_gainers = nse.get_top_gainers()
df_top_gainers = pd.DataFrame(top_gainers)
コード例 #16
0
ファイル: quoet.py プロジェクト: shivaneeshinde/nsetools
from pprint import pprint
from nsetools import Nse
nse = Nse()
nifty_quote = nse.get_index_quote('cnx nifty')
pprint(nifty_quote)
コード例 #17
0
import json
from nsetools import Nse
nse = Nse()
print(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)

p = nse.get_index_quote(
    "nifty bank")  # code can be provided in upper|lower case.

# pprint(p)

top_gainers = nse.get_top_gainers()

#print(top_gainers)
# pprint(top_gainers)

#data = json.load(top_gainers)

# for (k, v) in top_gainers.items():
#    print("Key: " + k)
#    print("Value: " + str(v))

# for key, value in enumerate(top_gainers):
#     print(value)
#     break

# for i in top_gainers:
#     print(i.symbol)
コード例 #18
0
ファイル: nse_tests.py プロジェクト: vsjha18/nsetools
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)
コード例 #19
0
ファイル: nse_tests.py プロジェクト: gavicharla/nsetools
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)
コード例 #20
0
ファイル: app.py プロジェクト: chinmxy/flask-chatbot
def webhook():
    nse = Nse()
    with open('symbols.json') as json_file:
        symbol_data = json.load(json_file)
    with open('inv_symbols.json') as json_file:
        inv_symbol_data = json.load(json_file)
    newsapi = NewsApiClient(api_key='cc0446450bcc4e46a91abd02e33d5f85')

    req = request.get_json(silent=True, force=True)
    query_result = req.get('queryResult')

    if query_result.get('action') == 'get_stock_price':
        # query_result = req.get('queryResult')
        price_type = query_result.get('parameters').get('price_type')
        company_name = query_result.get('parameters').get('company_name')
        date_time = query_result.get('parameters').get('date-time')
        if isinstance(date_time, str):
            s = date_time.split("T")[0]
            unix_time = int(
                time.mktime(
                    datetime.datetime.strptime(s, "%Y-%m-%d").timetuple()))
        else:
            s = date_time['date_time'].split("T")[0]
            unix_time = int(
                time.mktime(
                    datetime.datetime.strptime(s, "%Y-%m-%d").timetuple()))
        start_date = unix_time
        end_date = unix_time + 86399
        try:
            company_symbol = symbol_data[company_name]
        except:
            return {
                "fulfillmentText":
                "Sorry! You need to enter a NSE belonging company.",
                "displayText": '25',
                "source": "webhookdata"
            }
        q = nse.get_quote(company_symbol)
        prices = {
            "opening": q['open'],
            "closing": q['lastPrice'],
            "high": q['dayHigh'],
            "low": q['dayLow']
        }
        human_readable_date = datetime.datetime.utcfromtimestamp(
            unix_time).strftime("%d %B, %Y")
        op_string = "The {} price of {} on {} was Rs.{}.".format(
            price_type, company_name, human_readable_date, prices[price_type])

        return {
            "fulfillmentText": op_string,
            "displayText": '25',
            "source": "webhookdata"
        }
    elif query_result.get('action') == 'get_gainer':
        gainer_type = query_result.get('parameters').get('gainer_type')
        if query_result.get('parameters').get('number') == '':
            number = 1
        else:
            number = int(query_result.get('parameters').get('number'))
        top_gainers = nse.get_top_gainers()
        top_losers = nse.get_top_losers()

        if gainer_type == 'gainer':
            if number == 1:
                c_name = inv_symbol_data[top_gainers[0].get('symbol')]
                op_string = "The top gainer for the last trading session is {}.".format(
                    c_name)
            else:
                company_list = []
                for i in range(number - 1):
                    company_list.append(
                        inv_symbol_data[top_gainers[i].get('symbol')])
                company_string = ", ".join(company_list)
                company_string += " and {}".format(
                    inv_symbol_data[top_gainers[number - 1].get('symbol')])
                op_string = "The top {} {}s are {}.".format(
                    number, gainer_type, company_string)
        else:
            if number == 1:
                c_name = inv_symbol_data[top_losers[0].get('symbol')]
                op_string = "The top loser for the last trading session is {}.".format(
                    c_name)
            else:
                company_list = []
                for i in range(number - 1):
                    company_list.append(
                        inv_symbol_data[top_losers[i].get('symbol')])
                company_string = ", ".join(company_list)
                company_string += " and {}".format(
                    inv_symbol_data[top_losers[number - 1].get('symbol')])
                op_string = "The top {} {}s are {}.".format(
                    number, gainer_type, company_string)

        return {
            "fulfillmentText": op_string,
            "displayText": '25',
            "source": "webhookdata"
        }

    elif query_result.get('action') == 'get_news':
        company_name = query_result.get('parameters').get('company_name')
        all_articles = newsapi.get_everything(
            qintitle=company_name,
            sources='bbc-news,the-verge,the-times-of-india',
            language='en',
            sort_by='relevancy')
        articles = all_articles.get('articles')
        if len(articles) == 0:
            return {
                "fulfillmentText": "Sorry! Could not find any relevant news.",
                "displayText": '25',
                "source": "webhookdata"
            }
        article = articles[random.randint(0, len(articles) - 1)]
        # pprint(article)
        title = article.get('title')
        url = article.get('url')
        url_img = article.get('urlToImage')
        subtitle = article.get('description')

        response = [{
            "card": {
                "title":
                title,
                "subtitle":
                subtitle,
                "imageUri":
                url_img,
                "buttons": [{
                    "text": "Read Full Story",
                    "postback": url
                }, {
                    "text":
                    "Get more news",
                    "postback":
                    "Get more news for {}".format(company_name)
                }]
            },
            "platform": "FACEBOOK"
        }]

        return jsonify({"fulfillmentMessages": response})

    elif query_result.get('action') == 'get_index_quote':
        index_code = query_result.get('parameters').get('index_codes')
        if index_code == "":
            op_string = 'Try again using a valid Index code.'
        else:
            index_quote = nse.get_index_quote(index_code).get('lastPrice')
            op_string = "The last updated price of {} is Rs.{}.".format(
                index_code.upper(), index_quote)

        return {
            "fulfillmentText": op_string,
            "displayText": '25',
            "source": "webhookdata"
        }

    elif query_result.get('action') == 'get_advances':
        trade_index = query_result.get('parameters').get('index_codes')
        advance_type = query_result.get('parameters').get('advance_type')

        print(trade_index)
        if trade_index == '':
            op_string = 'Try again using a valid Index code.'
        else:
            adv_dec = nse.get_advances_declines()

            flag = 0
            for i in adv_dec:
                if i.get('indice') == trade_index:
                    advances = i.get('advances')
                    declines = i.get('declines')
                    flag = 1
                    break
            if flag == 0:
                op_string = "No data of advances/declines for this index was found."
            else:
                if advance_type == 'advance':
                    op_string = "The advances of {} are {}.".format(
                        trade_index, advances)
                else:
                    op_string = "The declines of {} are {}.".format(
                        trade_index, declines)
            print(op_string)

        return {
            "fulfillmentText": op_string,
            "displayText": '25',
            "source": "webhookdata"
        }
コード例 #21
0
from nsetools import Nse
from time import sleep
nse=Nse()
while True:
    with open("/home/arya/Desktop/.stock-indices","r") as stocks:
        OUT="NSE:"
        for stock in stocks:
            symbol=stock.strip()
            quote=nse.get_index_quote(symbol)
            price=quote["lastPrice"]
            pchange=quote["pChange"]
            change=quote["change"]
            bg=""
            if float(change) < 0:
                ch=False
                bg="^bg(#600)^fg(#FFF) "
            else:
                ch=True
                bg="^bg(#060)^fg(#FFF) "
            OUT+=" ^fn(NotoSansMono:size=8)"+symbol+"^fn():^ca(1, sh ~/.config/bspwm/scripts/panel/assets/shell/stock_index_click.sh " + str(change) + ")"+"^fn(NotoSansMono:size=7) "+str(pchange)+" ^fn()^ca()"+bg+str(price)+" ^bg()^fg() "
        OUT+="\n"
        with open("/tmp/bspwm_finance_panel","w") as out:
            out.write(OUT)
        print(OUT)
        sleep(30)
        
コード例 #22
0
ファイル: nse_tests.py プロジェクト: prasobhpk/nsetools
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))
コード例 #23
0
ファイル: nse_tests.py プロジェクト: vbyravarasu/nsetools3
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_nse_headers(self):
        ret = self.nse.nse_headers()
        self.assertIsInstance(ret, dict)

    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_get_peer_companies(self):
        code = 'infy'
        response = self.nse.get_peer_companies(code)
        self.assertIsInstance(response, pd.DataFrame)

        # This one was causing a weird error. as the offset was different
        code = '63moons'
        response = self.nse.get_peer_companies(code)
        self.assertIsInstance(response, pd.DataFrame)

    def test_market_status(self):
        result = market_status()
        self.assertIsInstance(result, bool)

    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, pd.DataFrame)
        if sc.empty:
            self.fail()


# 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.assertEqual(self.nse.get_quote(wrong_code), None)

    def test_get_quote(self):
        resp = self.nse.get_quote('infy', '20Microns', 'abb')
        self.assertEqual(len(resp), 3)
        self.assertIsInstance(resp, pd.DataFrame)
        # test json response
        json_resp = self.nse.get_quote('infy',
                                       '20Microns',
                                       'abb',
                                       as_json=True)
        self.assertEqual(len(json_resp), 3)
        self.assertIsInstance(json_resp[0], str)

    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(self):
        # as_json = False
        # This test will remove the need to test the individual parts
        result = self.nse.get_top('gainers', 'losers', 'volume', 'active',
                                  'advances decline', 'index list', 'JUNK')
        # Gainers/Losers/Volume/Advances Decline is supposed to return a list of dictionaries
        # Index list is supposed to return a list of strings
        # JUNK Should not return anything
        temp = []
        for item in result:
            temp.append(item)

        self.assertEqual(6, len(temp))
        gainer, loser, volume, active, adv_decline, index_list = temp[0], temp[
            1], temp[2], temp[3], temp[4], temp[5]

        # Test these individually
        self.assertIsInstance(gainer, pd.DataFrame)

        self.assertIsInstance(loser, pd.DataFrame)

        self.assertIsInstance(volume, pd.DataFrame)

        self.assertIsInstance(adv_decline, pd.DataFrame)

        self.assertIsInstance(index_list, list)

        # Now as_json = True
        result = self.nse.get_top('gainers',
                                  'losers',
                                  'volume',
                                  'active',
                                  'advances decline',
                                  'index list',
                                  as_json=True)

        temp = []
        for item in result:
            temp.append(item)

        self.assertEqual(6, len(temp))
        gainer, loser, volume, active, adv_decline_json, index_list_json = temp[
            0], temp[1], temp[2], temp[3], temp[4], temp[5]

        self.assertIsInstance(gainer, str)
        self.assertIsInstance(loser, str)
        self.assertIsInstance(volume, str)
        self.assertIsInstance(active, str)

        self.assertIsInstance(adv_decline_json, str)
        self.assertEqual(len(adv_decline), len(json.loads(adv_decline_json)))

        self.assertIsInstance(index_list_json, str)
        self.assertListEqual(index_list, json.loads(index_list_json))

    def test_render_response(self):
        d = {'fname': 'Arkoprabho', 'lname': 'Chakraborti'}
        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_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_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):
        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_save_file(self):
        # Call the function, check if the file has been saved at the required location
        dataframe = self.nse.get_stock_codes()
        save_file(dataframe, 'csv', path=gettempdir(), name='StockCodes')
        path = os.path.join(gettempdir(), 'StockCodes.csv')
        if not os.path.exists(path):
            self.fail()

        save_file(dataframe, 'html', path=gettempdir(), name='StockCodes')
        path = os.path.join(gettempdir(), 'StockCodes.html')
        if not os.path.exists(path):
            self.fail()

        save_file(dataframe, 'json', path=gettempdir(), name='StockCodes')
        path = os.path.join(gettempdir(), 'StockCodes.json')
        if not os.path.exists(path):
            self.fail()

        save_file(dataframe, 'tex', path=gettempdir(), name='StockCodes')
        path = os.path.join(gettempdir(), 'StockCodes.tex')
        if not os.path.exists(path):
            self.fail()
コード例 #24
0
# Following variables are use in Option range and risk money caluculations
crkr = 0
prkr = 0
cbrkr = 0
pbrkr = 0
rkr = 0
brkr = 0
bcorm = 0
bporm = 0
nporm = 0
ncorm = 0

#NIFTY indexs current values

nf_indiavix = nse.get_index_quote("INDIA VIX")
print('INDIA VIX  index current value is {} and percent change is {} '.format(
    nf_indiavix['lastPrice'], nf_indiavix['pChange'], '.2f'))

nf_n50 = nse.get_index_quote("nifty 50")
print('NIFTY 50   index current value is {} and percent change is {} '.format(
    nf_n50['lastPrice'], nf_n50['pChange']))

nf_nxt50 = nse.get_index_quote("NIFTY NEXT 50")
print(
    'NIFTY NEXT 50 index current value is {} and percent change is {} '.format(
        nf_nxt50['lastPrice'], nf_nxt50['pChange'], '.2f'))

nf_bank = nse.get_index_quote("nifty bank")
print('NIFTY BANK index current value is {} and percent change is {} '.format(
    nf_bank['lastPrice'], nf_bank['pChange']))
コード例 #25
0
ファイル: trynsetools.py プロジェクト: gansai/python-examples
# Instantiating the driver class for National Stock Exchange
nse = Nse()

# Importing Pretty Print
from pprint import pprint

pprint('Getting Index Quote for Infosys')
pprint(nse.get_quote('infy'))

pprint('Getting the entire Index List')
indices = nse.get_index_list()
pprint(indices)

pprint('Getting Index Quote for a particular index')
pprint(nse.get_index_quote(indices[1]))

pprint('Getting Index Quote for all indices')
for x in indices:
    pprint(nse.get_index_quote(x))

pprint('Getting all Stock Codes')
all_stocks = nse.get_stock_codes()
pprint(all_stocks)

pprint('Getting Quotes for each stock')
for x in all_stocks:
    pprint(nse.get_quote(x))

pprint('Getting Advances & Declines')
pprint(nse.get_advances_declines())
コード例 #26
0
from email.mime.text import MIMEText

nse = Nse()

secInfo = open('security.info').read()
creds = json.loads(secInfo)

gmail_username = creds['Username']
gmail_password = creds['Password']
target_mail = creds['Target']

f = open('template.html')
template = f.read()
f.close()

stockDets = nse.get_index_quote('NIFTY 50')
lastPrice = stockDets['lastPrice']
pChange = stockDets['pChange']
color = "#FF0000" if float(pChange) < 0 else "#00FF00"
nifty50 = "<font color='" + color + "'>" + str(lastPrice) + "(" + str(
    pChange) + ")</font>"

stockDets = nse.get_index_quote('NIFTY IT')
lastPrice = stockDets['lastPrice']
pChange = stockDets['pChange']
color = "#FF0000" if float(pChange) < 0 else "#00FF00"
niftyit = "<font color='" + color + "'>" + str(lastPrice) + "(" + str(
    pChange) + ")</font>"

stockDets = nse.get_index_quote('NIFTY BANK')
lastPrice = stockDets['lastPrice']
コード例 #27
0
ファイル: get_real.py プロジェクト: AnuragTomar/predicto
#import nsetools
from nsetools import Nse
nse = Nse()
print(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)

nifty_quote = nse.get_index_quote(
    'cnx nifty')  # code can be provided in upper|lower case.
banknifty_quote = nse.get_index_quote(
    'banknifty')  # code can be provided in upper|lower case.
pprint(nifty_quote)

pprint(banknifty_quote)

all_stock_codes = nse.get_stock_codes()
pprint(all_stock_codes)

index_codes = nse.get_index_list()
pprint(index_codes)

adv_dec = nse.get_advances_declines()
pprint(adv_dec)

top_gainers = nse.get_top_gainers()
pprint(top_gainers)

nse.is_valid_code('infy')  # this should return True
コード例 #28
0
ファイル: dummy_ohl.py プロジェクト: tomdxb0004/JAANU
            #print(parameter,'******',json.loads(stock_details)[parameter])

            stocks_dict[stock].append(json.loads(stock_details)[parameter])
    df = pd.DataFrame.from_dict(
        stocks_dict,
        orient='index',
        columns=['HIGH', 'LOW', 'OPEN', 'LAST TRADED PRICE', '%change'])
    df.reset_index(inplace=True)
    df.rename(columns={'index': 'symbol'}, inplace=True)

    df.columns = [re.sub(r'\n', '', x.lower()) for x in df.columns]
    return df


dfx = get_stock_data()
nifty50 = nse.get_index_quote("nifty 100")
trend = float(nifty50['pChange'])

dfx['%change'] = dfx['%change'].astype(float)

capital = 400000
ideal_profit = 2
stop_loss = 0.5

if trend < 0:
    print('Pre-market downtrend')

    # for S
    dfx.loc[(dfx['open'] == dfx['high']), 'action'] = 'S'
    ohl_cand = dfx.dropna(how='any')
    ohl_cand.rename(columns={'last traded price': 'LTP'}, inplace=True)
コード例 #29
0
import winsound
from apscheduler.schedulers.blocking import BlockingScheduler
from nsetools import Nse
import pandas as pd
import math as m
import numpy

frequency1 = 2500  # Set Frequency To 2500 Hertz
duration1 = 1000  # Set Duration To 1000 ms == 1 second

frequency0 = 1500  # Set Frequency To 2500 Hertz
duration0 = 1000  # Set Duration To 1000 ms == 1 second


nse = Nse()
q = nse.get_index_quote('nifty bank')
print(q)
#This is where the time gets set

start_time = time.ctime()
index = start_time.index(':')
print(start_time,' ',)
leftSlice = slice(0,index-2)
rightSlice = slice(index+6,start_time.__len__())
rightPart = start_time[rightSlice]
leftPart = start_time[leftSlice]
start_time = leftPart+'12:00:00'+rightPart
wait_time = leftPart+'12:01:00'+rightPart


コード例 #30
0
#if len(df_lotsize_eqfnolosers_inx) >0:
#   print("Todays Top Equity compare to FnO losers with Lot size \n",df_lotsize_eqfnolosers_inx[0:],file=open("NSEFnO_Todays TopGL.txt", "a"))
#print('')

if len(df_lotsize_eqfnolosers_inx) > 0:
    df_eqfnolosers_join = pd.concat(
        [df_lotsize_eqfnolosers_inx, df_eqloserslist_sort],
        axis=1,
        join='inner')
    #print("Todays Top equity compare to FnO losers with Lot size \n",df_eqfnolosers_join[0:],file=open("NSEFnO_Todays TopGL.txt", "a"))

####################################### Main Logic ########################################

#Buying strategy

nf_n50 = nse.get_index_quote("nifty 50")
print('NIFTY 50 index current value is {} and precent change is {} '.format(
    nf_n50['lastPrice'], nf_n50['pChange']),
      file=open("NSEFnO_Todays TopGL.txt", "a"))

#Reseting the counters
fl = 0
fg = 0
eg = 0

if float(nf_n50['pChange']) >= 0.05:
    print("Todays BUY PUTs  from Top Losers Stock (TLS) list",
          file=open("NSEFnO_Todays TopGL.txt", "a"))
    print("Todays BUY CALLs from Top Gainers Stock (TGS) list",
          file=open("NSEFnO_Todays TopGL.txt", "a"))
    print("", file=open("NSEFnO_Todays TopGL.txt", "a"))
コード例 #31
0
from nsepy import get_rbi_ref_history
from nsepy import get_history
from nsepy import get_index_pe_history
from nsepy.history import get_price_list
from datetime import date
import pandas as pd
import numpy as np

PAGE_CONFIG = {"page_title": "SM APP", "layout": "centered"}
st.beta_set_page_config(**PAGE_CONFIG)
nse = Nse()

st.title("The Stock Market App")
st.header("What  changed in the market while you were asleep ?")
if st.button("Check Market"):
    q = nse.get_index_quote("nifty 50")
    r = nse.get_index_quote("nifty 500")
    s = nse.get_index_quote("nifty bank")
    st.write(q)
    st.write(r)
    st.write(s)

st.header("Have a look at the Top gainers today!")
if st.button("Check Gainers"):
    top_gainers = nse.get_top_gainers(10)
    st.write(top_gainers)

st.header("Have a look at the Top losers today!")
if st.button("Check Losers"):
    top_losers = nse.get_top_losers(5)
    st.write(top_losers)