def get_futures_data_LTP(symbol):
    current_date = datetime.datetime.now().date()
    current_year = current_date.year
    current_month = current_date.month
    current_expiry_date = get_expiry_date(year=current_year, month=current_month)
    if current_date > current_expiry_date:
        current_expiry_date = get_expiry_date(year=current_year, month=current_month+1)
        next_expiry_date = get_expiry_date(year=current_year, month=current_month + 2)
    else:
        next_expiry_date = get_expiry_date(year=current_year, month=current_month + 1)

    current_exp_quote = get_quote(symbol=symbol, instrument='FUTSTK', expiry=current_expiry_date, strike=450.00)
    next_exp_quote = get_quote(symbol=symbol, instrument='FUTSTK', expiry=next_expiry_date, strike=450.00)
    print(current_exp_quote)
    print(next_exp_quote)
    # current_exp_quote_lastPrice = current_exp_quote['lastPrice']
    # next_exp_quote_lastPrice = next_exp_quote['lastPrice']

    # make current_expiry_ltp = current_month_buyPrice1 from spread
    # make next_expiry_ltp = next_month_sellPrice1 from spread
    # becasue this will be only the sell spread: Buying current month, selling next month
    current_exp_quote_lastPrice = current_exp_quote['sellPrice1']
    next_exp_quote_lastPrice = next_exp_quote['buyPrice1']
    print(current_exp_quote_lastPrice)
    print(next_exp_quote_lastPrice)
    if current_exp_quote_lastPrice == '-':
        current_exp_quote_lastPrice = 0.0
    if next_exp_quote_lastPrice == '-':
        next_exp_quote_lastPrice = 0.0

    if current_exp_quote_lastPrice > 1 and next_exp_quote_lastPrice > 1:
        return current_exp_quote_lastPrice, next_exp_quote_lastPrice;
    else:
        return 0.0, 0.0;
Example #2
0
def live_quote(share_code="indigo"):
    if type(share_code) != list:
        share_code = list(share_code.split())
    share_code = [code.upper() for code in share_code]
    req_columns = [
        'symbol', 'lastPrice', 'totalTradedVolume', 'open', 'dayHigh',
        'dayLow', 'previousClose'
    ]
    rename_col = ['symbol', 'LTP', 'Vol', 'Open', 'High', 'Low', 'PrevClose']
    req_df = pd.DataFrame(columns=rename_col)
    for code in share_code:
        live_data = json_normalize(get_quote(code))
        temp_data = live_data[req_columns]
        temp_data.columns = rename_col
        req_df = req_df.append(temp_data)
    return req_df
Example #3
0
def calculate_toplosers(filename):
    folder = os.getcwd()
    destination = str(folder) + '\symbols'
    file_name = destination + '\\' + str(filename)
    df = pd.read_csv(file_name)

    data = df['data']
    top_mover_symbol = []
    top_mover_price = []
    top_mover_change = []
    top_mover_pchange = []

    for d in data:
        try:
            e = d.split("'")
            symbol = e[1]
            q = nsepy.get_quote(symbol)
            q_data = dict(q['data'][0])

            change = q_data['change']
            pchange = int(float(q_data['pChange']))
            lastPrice = q_data['lastPrice']
            print(symbol)
            if pchange < -2 and int(float(change)) < 0:
                print(symbol)
                top_mover_symbol.append(symbol)
                top_mover_price.append(lastPrice)
                top_mover_change.append(change)
                top_mover_pchange.append(pchange)
        except:
            print('Bad symbol')

    dict_top_mover = {
        'symbol': top_mover_symbol,
        'price': top_mover_price,
        'change': top_mover_change,
        'pchange': top_mover_pchange
    }

    df = pd.DataFrame(dict_top_mover)

    out = '\\toplosers\\toplosers' + str(filename)
    out = folder + out
    df.to_csv(out)
Example #4
0
 def get_ltp(stock):
     ltp = get_quote(symbol=stock)['lastPrice']
     return ltp
Example #5
0
from nsepy import get_history
from nsepy import get_quote
from datetime import date
import pandas as pd
import matplotlib.pyplot as plt
from pandas.plotting import register_matplotlib_converters

register_matplotlib_converters()

stock = "ZEEL"
expiry = date(2019, 4, 25)

# def get_quote(symbol, series='EQ', instrument=None, expiry=None, option_type=None, strike=None):
data_stock = get_quote(symbol=stock, series='EQ', expiry=date(2019, 4, 25))
print("DEBUG: Option Price")
print(data_stock)

#  Call to get the live option price
data_option1 = get_quote(symbol=stock,
                         series='EQ',
                         instrument='OPTSTK',
                         option_type='CE',
                         strike=450,
                         expiry=date(2019, 4, 25))

print("DEBUG: Option Price")
print(data_option1)
def plotTheGraph(stock):
    today = date.today()
    currentExpiryDate = get_expiry_date(today.year, today.month)
    # if(today>currentExpiryDate):
    #     currentExpiryDate = get_expiry_date(today.year,today.month+1)
    #     prevExpiryDate = get_expiry_date(today.year,today.month)
    #     futureExpiryDate = get_expiry_date(today.year, today.month + 2)
    # else :
    #     currentExpiryDate = get_expiry_date(today.year, today.month)
    #     prevExpiryDate = get_expiry_date(today.year, today.month-1)
    #     if(today.month != 12):
    #         futureExpiryDate = get_expiry_date(today.year, today.month + 1)
    #     else:
    #         futureExpiryDate = get_expiry_date(today.year+1, 1)

    currentExpiryDateSet = get_expiry_date(today.year, today.month)
    prevExpiryDateSet = get_expiry_date(today.year, today.month - 1)
    if (today.month != 12):
        futureExpiryDateSet = get_expiry_date(today.year, today.month + 1)
    else:
        futureExpiryDateSet = get_expiry_date(today.year + 1, 1)

    currentExpiryDate = sorted(currentExpiryDateSet, reverse=True)[0]
    prevExpiryDate = sorted(prevExpiryDateSet, reverse=True)[0]
    futureExpiryDate = sorted(futureExpiryDateSet, reverse=True)[0]

    start = prevExpiryDate - timedelta(15)
    end = today  #date(2018,12,27)
    print('start', start)
    print('end', end)
    end2 = today

    index = False
    future = True

    instrument = 'FUTSTK'
    instrumentArray = ['NIFTY', 'BANKNIFTY']
    if stock in instrumentArray:
        instrument = 'FUTIDX'
        index = True
        future = False

    # Live Data
    liveData = get_quote(symbol=stock,
                         instrument=instrument,
                         expiry=currentExpiryDate,
                         option_type='-',
                         strike=700)

    #Pivot table code
    liveData = pd.DataFrame.from_dict(liveData, orient='index')
    # liveData = pd.DataFrame(liveData,columns=['column','values'])
    # liveData['index'] = np.arange(len(liveData))
    # liveData = liveData.reset_index().set_index('index')

    # liveData.pivot(columns='level_0',values='0')
    # print(liveData)

    ltp = liveData.get('ltp', 0)
    volume = liveData.get('numberOfContractsTraded', 0)
    # print("Today's volume: ",volume)
    chngOI = liveData.get('changeinOpenInterest', 0)
    # print("Today's OI: ",chngOI)

    # print("live: ",liveData)
    # print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")

    data_fut = get_history(symbol=stock,
                           index=index,
                           futures=future,
                           start=start,
                           end=end,
                           expiry_date=currentExpiryDate)
    data_fut2 = get_history(symbol=stock,
                            index=index,
                            futures=future,
                            start=start,
                            end=end2,
                            expiry_date=futureExpiryDate)

    # pd.DataFrame(data_fut, index=data_fut['Date'].strftime("%b %d")).style.format("{:.2}")
    # pd.DataFrame(data_fut2, index=data_fut..strftime("%b %d")).style.format("{:.2}")

    if instrument == 'FUTSTK':
        OI_combined = pd.concat(
            [data_fut2['Open Interest'], data_fut['Open Interest']],
            axis=1,
            sort=False)
        OI_combined['OI_Combined'] = OI_combined.sum(axis=1) + int(chngOI)
        # print("Open Interest: ",OI_combined['OI_Combined'])
        # OI_combined['OI_Combined'] = OI_combined['OI_Combined'] + chngOI

        # No. of contracts
        volume_combined = pd.concat([
            data_fut2['Number of Contracts'], data_fut['Number of Contracts']
        ],
                                    axis=1,
                                    sort=False)
        volume_combined['volume_combined'] = volume_combined.sum(
            axis=1) + int(volume)
        # print("Volume : ",volume_combined['volume_combined'])
        # print("volume_combined['volume_combined'] = ",volume_combined['volume_combined'])
        # volume_combined['volume_combined'] = volume_combined['volume_combined'] + volume
    else:
        # No. of contracts
        volume_combined = pd.concat([data_fut2['Volume'], data_fut['Volume']],
                                    axis=1,
                                    sort=False)
        volume_combined['volume_combined'] = volume_combined.sum(axis=1)
        # print("volume_combined['volume_combined'] = ",volume_combined['volume_combined'])
        # volume_combined['volume_combined'] = volume_combined['volume_combined'] + volume

    # Rule to throw an alert
    # Display Underlying
    plt.subplot(222)
    plt.title('Underlying')
    # priceCombined= pd.concat([data_fut['Underlying'],data_fut2['Underlying']],axis=1,sort=False)
    # plt.plot(priceCombined,color='green')
    plt.plot(data_fut['Last'], color='green')
    # plt.plot(pd.concat(data_fut['Last'],liveData.get('ltp',0)), color='green')
    plt.legend(['Last'])
    plt.xlabel('Date')
    plt.ylabel('Price')
    # plt.xlabel.set_major_formatter(mdates.DateFormatter('%b %d'))

    # Display Volumes
    plt.subplot(224)
    plt.title('Volume')
    plt.plot(volume_combined.volume_combined, label='Volume', color='blue')
    plt.plot(volume_combined.volume_combined.rolling(5).mean(),
             label='Volume',
             color='orange')
    plt.legend(['Volume', 'Volume_mean'])
    plt.xlabel('Date')
    plt.ylabel('Volume')
    # plt.xlabel.set_major_formatter(mdates.DateFormatter('%b %d'))

    # Display Cumulative Open Interest
    plt.figure(1, figsize=(10, 9))
    plt.subplot(221)
    plt.title('Open Interest')
    plt.plot(OI_combined.OI_Combined, label='OI')
    plt.plot(OI_combined.OI_Combined.rolling(5).mean(), label='OI')

    plt.xlabel('Date')
    plt.ylabel('Open Interest')
    # plt.xlabel.set_major_formatter(mdates.DateFormatter('%b %d'))

    fig = pylab.gcf()
    fig.canvas.set_window_title(stock)
    plt.legend(['OI', 'OI_mean'])

    plt.show()
    stock = input("Enter the Future Symbol here: ")
    if stock == "":
        plt.close(fig)
        return
    else:
        plt.close(fig)
        plotTheGraph(stock=stock)
Example #7
0
def fetch_periodic_data(nifty_codes):
    sourceFile = open(dyn_file_name, 'a+')
    source_file_consolidate = open('LiveDataConsolidated.txt', 'w')
    print(fmt.format('UNDERLYING', 'TIMESTAMP', 'OPEN', 'HIGH', 'LOW', 'LAST',
                     'ULAST', 'VOL', 'AVGVOL', 'VOLSGNL', 'CHOI', '%PREM',
                     '%PR', '%OI', '%VOL', 'MON_INV_MLL'),
          file=source_file_consolidate)
    sourceFile.flush()
    ts = time.time()
    st = datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
    print("fetchPeriodicData started @ ", st)

    for index, row in nifty_codes.iterrows():
        # Historical data to get average volume of last 3 days
        historicalData = get_history(symbol=row['Symbol'],
                                     start=startDate,
                                     end=endDate,
                                     futures=True,
                                     expiry_date=currentExpiryDate)
        # expiry_date=datetime(2020, 5, 28))
        avgVolume = pd.DataFrame.mean(historicalData['Number of Contracts'])

        liveData = get_quote(symbol=row['Symbol'],
                             instrument='FUTSTK',
                             expiry=currentExpiryDate,
                             option_type='-',
                             strike=100)
        # print("keys :: ", liveData)
        volume = 0 if liveData.get(
            'numberOfContractsTraded') is None else liveData.get(
                'numberOfContractsTraded')

        if volume > calc_avg_vol_wrt_time(avgVolume) and liveData.get(
                'underlying') not in stk_ts_dict.keys():
            stk_ts_dict[liveData.get('underlying')] = liveData.get('lastPrice')
            msg = liveData.get('underlying') + ' crossed volume at '+ \
                  datetime.fromtimestamp(ts).strftime('%H:%M ') \
                  + str(liveData.get('lastPrice'))
            # telegram_send.send(conf='telegram.conf', messages=[msg])

        try:
            print(
                fmt.format(
                    liveData.get('underlying'),
                    datetime.fromtimestamp(time.time()).strftime(
                        '%Y-%m-%d %H:%M:%S'),  #liveData.get('lastUpdateTime')
                    liveData.get('openPrice'),
                    liveData.get('highPrice'),
                    liveData.get('lowPrice'),
                    liveData.get('lastPrice'),
                    liveData.get('underlyingValue'),
                    liveData.get('numberOfContractsTraded'),
                    int(avgVolume),
                    stk_ts_dict[liveData.get('underlying')]
                    if calc_avg_vol_wrt_time(avgVolume) < volume else '',
                    liveData.get('changeinOpenInterest'),
                    str(
                        round(
                            float(liveData.get('lastPrice')) -
                            float(liveData.get('underlyingValue')) * 100 /
                            float(liveData.get('lastPrice')), 2)),
                    liveData.get('pChange'),
                    liveData.get('pchangeinOpenInterest'),
                    int(
                        liveData.get('numberOfContractsTraded') * 100 /
                        int(avgVolume)),
                    abs(
                        int((liveData.get('changeinOpenInterest') *
                             liveData.get('lastPrice')) / 1000000))),
                file=sourceFile)
            print(fmt.format(
                liveData.get('underlying'),
                datetime.fromtimestamp(
                    time.time()).strftime('%Y-%m-%d %H:%M:%S'),
                liveData.get('openPrice'), liveData.get('highPrice'),
                liveData.get('lowPrice'), liveData.get('lastPrice'),
                liveData.get('underlyingValue'),
                liveData.get('numberOfContractsTraded'), int(avgVolume),
                stk_ts_dict[liveData.get('underlying')]
                if calc_avg_vol_wrt_time(avgVolume) < volume else '',
                liveData.get('changeinOpenInterest'),
                str(
                    round((float(liveData.get('lastPrice')) -
                           float(liveData.get('underlyingValue'))) * 100 /
                          float(liveData.get('lastPrice')), 2)),
                liveData.get('pChange'), liveData.get('pchangeinOpenInterest'),
                int(
                    liveData.get('numberOfContractsTraded') * 100 /
                    int(avgVolume)),
                abs(
                    int((liveData.get('changeinOpenInterest') *
                         liveData.get('lastPrice')) / 1000000))),
                  file=source_file_consolidate)

        except:
            print(fmt.format(
                row['Symbol'],
                datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'),
                "" if liveData.get('openPrice') is None else
                liveData.get('openPrice'),
                "" if liveData.get('highPrice') is None else
                liveData.get('highPrice'), "" if
                liveData.get('lowPrice') is None else liveData.get('lowPrice'),
                "" if liveData.get('lastPrice') is None else
                liveData.get('lastPrice'),
                "" if liveData.get('underlyingValue') is None else
                liveData.get('underlyingValue'),
                "" if liveData.get('numberOfContractsTraded') is None else
                liveData.get('numberOfContractsTraded'),
                "" if avgVolume is None else int(avgVolume), '',
                "" if liveData.get('changeinOpenInterest') is None else
                liveData.get('changeinOpenInterest'), '', "" if
                liveData.get('pChange') is None else liveData.get('pChange'),
                "" if liveData.get('pchangeinOpenInterest') is None else
                liveData.get('pchangeinOpenInterest'), '', ''),
                  file=sourceFile)
            print(fmt.format(
                row['Symbol'],
                datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'),
                "" if liveData.get('openPrice') is None else
                liveData.get('openPrice'),
                "" if liveData.get('highPrice') is None else
                liveData.get('highPrice'), "" if
                liveData.get('lowPrice') is None else liveData.get('lowPrice'),
                "" if liveData.get('lastPrice') is None else
                liveData.get('lastPrice'),
                "" if liveData.get('underlyingValue') is None else
                liveData.get('underlyingValue'), "" if
                liveData.get('pChange') is None else liveData.get('pChange'),
                "" if liveData.get('pchangeinOpenInterest') is None else
                liveData.get('pchangeinOpenInterest'),
                "" if liveData.get('numberOfContractsTraded') is None else
                liveData.get('numberOfContractsTraded'),
                "" if avgVolume is None else int(avgVolume), '',
                "" if liveData.get('changeinOpenInterest') is None else
                liveData.get('changeinOpenInterest'), '', "" if
                liveData.get('pChange') is None else liveData.get('pChange'),
                "" if liveData.get('pchangeinOpenInterest') is None else
                liveData.get('pchangeinOpenInterest'), '', ''),
                  file=source_file_consolidate)

        sourceFile.flush()
        source_file_consolidate.flush()
    sourceFile.close()
    source_file_consolidate.close()
Example #8
0
 def get_current_price(self):
     current_quote = nse.get_quote(self.tracker)
     self.current_price = current_quote['lastPrice']
     return self.current_price
#     print(" ******************** Data size is not same: So exiting the program  ******************** ")
#     sys.exit()
#
# close_price_history_stock01 = history_stock01[['Close']]
# close_price_history_stock02 = history_stock02[['Close']]
#
# print(history_stock01.tail(5))
# print(history_stock02.tail(5))
#
# merged_data = pd.concat([close_price_history_stock01, close_price_history_stock02], axis=1)
# merged_data.to_csv('/Users/ashok/king/Study/T/system/new_data_pipeline/data-pipeline/data/'+stock01+'_'+stock02+'.csv',index = True , header = [stock01,stock02] )

# stock_data = pd.read_csv('/Users/ashok/king/Study/T/system/new_data_pipeline/data-pipeline/data/'+stock01+'_'+stock02+'.csv', low_memory=False)
stock_data = pd.read_csv('/Users/ashok/king/Study/T/system/new_data_pipeline/data-pipeline/data/BANKBARODA_RBLBANK.csv', low_memory=False)
# Get LTP - Quote
quote_stock01 = get_quote(symbol=stock01)
quote_stock02 = get_quote(symbol=stock02)
ltp_stock01 = quote_stock01['lastPrice']
ltp_stock02 = quote_stock02['lastPrice']
# print("LTP of "+stock01+" == "+str(ltp_stock01))
# print("LTP of "+stock02+" == "+str(ltp_stock02))

# Decide which one to be used as X and which one as Y
model_1vs2 = smf.ols(stock01+' ~ '+stock02, data=stock_data)
results_1vs2 = model_1vs2.fit()
model_2vs1 = smf.ols(stock02+' ~ '+stock01, data=stock_data)
results_2vs1 = model_2vs1.fit()

# Residual Output Section
residuals_1vs2 = results_1vs2.resid
residuals_2vs1 = results_2vs1.resid