Running Code for Options/Stocks- open/high/low/close/ltp


  • Hi All,

    Just shairng a running code to get Options and Stocks live prices. As i have already invested time to build this, you may leverage on this and get a head start :-)

    Step 1: Get universe of tickers (stock/options) using this code:

    import pandas as pd
    import requests
    import numpy as np
    
    # Get Nifty 50 Tickers
    nifty50df = pd.read_excel (r'C:\Users\sukhw\OneDrive\Documents\Options\Staticdata.xlsx', sheet_name= 'IndexMembers')  
    
    # -----------------------------------Get the list of Options tickers as per expiry date
    urlk = "https://margincalculator.angelbroking.com/OpenAPI_File/files/OpenAPIScripMaster.json"
    resp = requests.get(urlk)
    data1 = resp.json()
    tickerlist = pd.json_normalize(data1,errors='ignore')
    
    # select Option Tickers from the list
    optiontickerlist = tickerlist[(tickerlist['exch_seg'] == 'NFO') & (tickerlist['instrumenttype'] == 'OPTSTK')]
    
    # select Stock Tickers from the list
    stocktickerlist = tickerlist[(tickerlist['exch_seg'] == 'NSE') & (tickerlist['symbol'].str.contains('-EQ', regex = True) == True)]
    stocktickerlist['expiry'] = np.where(stocktickerlist.index%2==0, 'stock', 'stock') 
    
    #append the above tables
    alltickers = pd.concat([optiontickerlist,stocktickerlist], sort =False).reset_index()
    
    # Assign columns to Dataframe 
    alltickers = alltickers[['symbol', 'token','name','expiry','strike','lotsize','instrumenttype','exch_seg','tick_size']]
    
    # Join the tables
    tickerAll = pd.merge(alltickers, nifty50df, left_on=['name'], right_on=['Symbol'], how='inner')
    
    # Drop the columns
    tickerAll = tickerAll.drop(['Symbol'], axis = 1)
    
    # Export the data
    tickerAll.to_excel (r'C:\Users\sukhw\OneDrive\Documents\Options\OptionTickers.xlsx', index = None, header=True)
    

    Step 2: Now get Prices for select tickers you want to monitor on daily basis:

    import pandas as pd
    import datetime as dt
    from smartapi import SmartConnect
    from datetime import date, timedelta
    
    # Now get Prices for select Tickers as per your requirement
    
    def getprices():
        
        vdate = (dt.datetime.today() - dt.timedelta(days=0)).strftime("%d%m%Y")
        
        
        # Get Tickers (either Stock or Options) you want to focus on for your daily monitoring
        tickerdf = pd.read_excel (r'C:\Users\sukhw\OneDrive\Documents\Options\SpecificTickers.xlsx', sheet_name= 'Sheet1')  
        
        
        # Setting the access to get  Open, high, Low, Close, LTP of options
        
        smartApi =SmartConnect(api_key="YourKey")
        login = smartApi.generateSession('YourClientID', 'YourPassword') # Angel broking
        refreshToken = login['data']['refreshToken']
        feedToken = smartApi.getfeedToken()
        smartApi.getProfile(refreshToken)
        smartApi.generateToken(refreshToken)
        
        
        
        prices_df = pd.DataFrame()
        
        # ------------------------------------ get Open, high, Low, Close, LTP of the Option Tikcers
        
        for index,row in tickerdf.iterrows():
                
            exchange = row['exch_seg']
            tradingsymbol = row['Ticker']
            symboltoken = int(row['Token'])
             
            data = smartApi.ltpData(exchange, tradingsymbol, symboltoken)
            prices = pd.json_normalize(data['data'],errors='ignore')
            
            prices['BussDate'] = vdate
            
            prices_df = prices_df.append(prices).reset_index(drop=True)
        
        # Export the data
        prices_df.to_excel (r'C:\Users\sukhw\OneDrive\Documents\Options\OptionPrices.xlsx', index = None, header=True)
        prices_df.to_excel (r'C:\Users\sukhw\OneDrive\Documents\Options\OptionPrices\OptionPrices{}.xlsx'.format(vdate), index = None, header=True)
    

    Any questions, feel free

    thanks
    Sukhwant


  • Dear Sukhwant,
    Could you send me the statistics.xlsx file for the tokens or let me know the source from where you have downloaded it. Because it is little difficult for me to identify token from the .json link that is provided by the smartapi.

    Thank you for the code.

    Regards,
    Anvesh Raja