Create a Function to get the High and Low of the Stock​

The significance of a stock’s price high lies in the following aspects:

  1. It serves as the stoploss level for a sell trade when the sell order is activated.
  2. It acts as the trigger point for initiating a buy trade.

Similarly, the low price of a stock holds importance for the following reasons:

  1. It functions as the stoploss level for a buy trade once the buy order is executed.
  2. It serves as the trigger point for initiating a sell trade.

In summary:

  • High of the stock = Buy Trigger = Sell Stoploss
  • Low of the stock = Sell Trigger = Buy Stoploss

Now, let’s consider the scenario where we want to determine if yesterday’s NIFTY had an inside bar. How about creating a function that provides us with the high and low prices of the stock on that particular day? This information can be used to assess whether a trade has been triggered or if it has hit its stop loss, among other things.

				
					def get_stock_data(symbol, time):   
    try:        
        datetime_string = str(row['date']) + " 9:20:00+05:30"
        parsed_datetime = datetime.datetime.strptime(datetime_string, '%d-%m-%Y %H:%M:%S%z')
        previous_day = parsed_datetime - datetime.timedelta(days=1)
        from_date = previous_day        
        
        data = kite.historical_data(instrument_token=get_insToken(symbol,"NSE"),
                                     from_date=from_date,
                                     to_date=from_date+ datetime.timedelta(days=2),
                                     interval='day')
    
        return data[0]['high'],data[0]['low'],data[1]['open']
        
    except IndexError:
        return 0,0,0
				
			

Now let’s explain the entire code step by step –

The get_stock_data function takes two parameters: symbol (like the stock symbol, e.g., ‘RELIANCE’) and time .

				
					    datetime_string = str(row['date']) + " 9:20:00+05:30"
    parsed_datetime = datetime.datetime.strptime(datetime_string, '%d-%m-%Y %H:%M:%S%z')

				
			
This line subtracts one day from the parsed_datetime to calculate the date for the previous trading day. The result is stored in the previous_day variable.
				
					    data = kite.historical_data(instrument_token=get_insToken(symbol,"NSE"),
                                 from_date=from_date,
                                 to_date=from_date+ datetime.timedelta(days=2),
                                 interval='day')
    return data[0]['high'], data[0]['low'], data[1]['open']

				
			
This section utilizes an external API or library called kite to fetch historical stock data. It specifies the instrument token, date range, and data interval. The retrieved data is stored in the data variable. Sometimes there can be trading holidays. So we are taking 2 days of data and checking for the last value using data[0].
Post a comment

Leave a Comment

Your email address will not be published. Required fields are marked *

×Close