Identify NR7 Candles for a stock Using Python and Zerodha

To go ahead with this tutorial, One must complete the pre-requsite tutorial which shows how to scan candles from Reliance Stock to spot which ones are having Narrow Range 4 (NR4) Bar Pattern –

Narrow Range 7 (NR7) Pattern:

The Narrow Range 7 (NR7) is a candlestick pattern used in technical analysis to identify potential price breakouts or significant moves in the financial markets. This pattern is particularly useful for traders and investors seeking to identify periods of consolidation or tight trading ranges that may precede a strong directional move.

Characteristics of the NR7 Pattern:

  1. Seven-Day Range: The name “NR7” stands for “Narrow Range 7,” which means it looks at a seven-day trading range. In other words, it analyzes the trading ranges of the past seven trading days.
  2. Smallest Range: The NR7 pattern occurs when the current trading day has the narrowest trading range among the previous six trading days.
  3. Consolidation: NR7 patterns often indicate a period of consolidation or contraction in price volatility. Traders interpret this as a potential calm before a storm, where a significant price move may follow.
  4. Breakout Potential: While the NR7 pattern doesn’t specify the direction of the breakout, it alerts traders to be prepared for a potential price breakout or significant move.

				
					# Iterate through historical data to detect NR7 candles for this batch
    for i in range(6, len(historical_data)):
        current_candle = historical_data[i]

        # Calculate the trading range for the previous six candles
        previous_candles = historical_data[i - 6:i]
        trading_ranges = [candle['high'] - candle['low'] for candle in previous_candles]

        # Check if the current candle has the narrowest range among the previous six
        if min(trading_ranges) == trading_ranges[-1]:
            nr7_candles.append(current_candle)
				
			

Changes in the Code to Detect NR7 Candles:

Adjust Range Calculation: In the NR4 code, we calculated the trading range for the previous three candles (3-day range). For NR7, we need to calculate the trading range for the previous six candles (6-day range). This change is reflected in the following line:

Iteration through Historical Data: We iterate through the historical price data for RELIANCE, starting from the fourth data point. This is because we need to assess the trading range of the previous three trading days for each candle.

				
					for i in range(6, len(historical_data)):
				
			
We start iterating from the seventh candle to calculate the 6-day trading range.

Check for Narrowest Range: The logic to check if the current candle has the narrowest range among the previous six candles remains the same. This condition helps identify NR7 candles.

				
					if min(trading_ranges) == trading_ranges[-1]:
				
			

Identifying NR4 Candle: We check if the current candle has the narrowest trading range among the previous three trading days. If the minimum trading range in the trading_ranges list corresponds to the current candle, it signifies that the current day’s price range is narrower than the previous three days.

				
					    # Check if the current candle has the narrowest range among the previous three
    if min(trading_ranges) == trading_ranges[-1]:
        nr4_candles.append(current_candle)

				
			
This line ensures that the current candle’s trading range is the smallest among the previous six, indicating an NR7 pattern.

Final Code to detect NR7 Candles in Reliance

So, Here goes the complete code that will scan the Narrow Range 7 (NR7) candles accurately in Reliance –

				
					from datetime import datetime, timedelta

# Define the date range
start_date = datetime.strptime('2023-01-01', '%Y-%m-%d')
end_date = datetime.strptime('2023-09-01', '%Y-%m-%d')

# Define the interval (in minutes)
interval = 'day'

# Initialize variables to track NR7 candles
nr7_candles = []

# Iterate through smaller date ranges (each within 60 days)
while start_date < end_date:
    # Calculate the end date for the current batch (within 60 days)
    batch_end_date = start_date + timedelta(days=60)

    # Ensure that the batch end date does not exceed the overall end date
    if batch_end_date > end_date:
        batch_end_date = end_date

    # Fetch historical data for the current batch
    historical_data = kite.historical_data(instrument_token, start_date, batch_end_date, interval)

    # Iterate through historical data to detect NR7 candles for this batch
    for i in range(6, len(historical_data)):
        current_candle = historical_data[i]

        # Calculate the trading range for the previous six candles
        previous_candles = historical_data[i - 6:i]
        trading_ranges = [candle['high'] - candle['low'] for candle in previous_candles]

        # Check if the current candle has the narrowest range among the previous six
        if min(trading_ranges) == trading_ranges[-1]:
            nr7_candles.append(current_candle)

    # Move the start date for the next batch
    start_date = batch_end_date

# Print or post detected NR7 candles for the entire date range
for candle in nr7_candles:
    print(f"NR7 Candle detected at {candle['date']} for RELIANCE")

				
			

The output comes perfectly fine. The number of NR7 Patterns in the stock is always significantly lower than NR4 by its definition – 

				
					NR7 Candle detected at 2023-01-19 00:00:00+05:30 for RELIANCE
NR7 Candle detected at 2023-01-20 00:00:00+05:30 for RELIANCE
NR7 Candle detected at 2023-02-03 00:00:00+05:30 for RELIANCE
NR7 Candle detected at 2023-02-08 00:00:00+05:30 for RELIANCE
NR7 Candle detected at 2023-02-17 00:00:00+05:30 for RELIANCE
NR7 Candle detected at 2023-02-27 00:00:00+05:30 for RELIANCE
NR7 Candle detected at 2023-03-16 00:00:00+05:30 for RELIANCE
NR7 Candle detected at 2023-03-24 00:00:00+05:30 for RELIANCE
NR7 Candle detected at 2023-03-29 00:00:00+05:30 for RELIANCE
NR7 Candle detected at 2023-04-11 00:00:00+05:30 for RELIANCE
NR7 Candle detected at 2023-04-12 00:00:00+05:30 for RELIANCE
NR7 Candle detected at 2023-04-27 00:00:00+05:30 for RELIANCE
NR7 Candle detected at 2023-05-12 00:00:00+05:30 for RELIANCE
NR7 Candle detected at 2023-05-22 00:00:00+05:30 for RELIANCE
NR7 Candle detected at 2023-05-31 00:00:00+05:30 for RELIANCE
NR7 Candle detected at 2023-06-09 00:00:00+05:30 for RELIANCE
NR7 Candle detected at 2023-07-26 00:00:00+05:30 for RELIANCE
NR7 Candle detected at 2023-08-10 00:00:00+05:30 for RELIANCE
NR7 Candle detected at 2023-08-14 00:00:00+05:30 for RELIANCE
NR7 Candle detected at 2023-08-28 00:00:00+05:30 for RELIANCE
				
			

Running NR7 Scanner on Cipla

Similarly, to maintain the continuity of the last chapter, Let’s run the Narrow Range 7 (NR7) Scanner on Cipla as well. 

Here is the modified code – 

				
					from datetime import datetime, timedelta

# Define the date range
start_date = datetime.strptime('2023-01-01', '%Y-%m-%d')
end_date = datetime.strptime('2023-09-18', '%Y-%m-%d')

# Define the interval (in minutes)
interval = 'day'

# Initialize variables to track NR7 candles
nr7_candles = []

# Define the stock symbol for CIPLA
symbol = 'NSE:CIPLA'

# Fetch instrument data for CIPLA
instruments = kite.ltp([symbol])

# Check if the instrument token for CIPLA is in the instruments dictionary
if symbol in instruments:
    instrument_token = instruments[symbol]['instrument_token']

    # Iterate through smaller date ranges (each within 60 days)
    while start_date < end_date:
        # Calculate the end date for the current batch (within 60 days)
        batch_end_date = start_date + timedelta(days=60)

        # Ensure that the batch end date does not exceed the overall end date
        if batch_end_date > end_date:
            batch_end_date = end_date

        # Fetch historical data for the current batch
        historical_data = kite.historical_data(instrument_token, start_date, batch_end_date, interval)

        # Iterate through historical data to detect NR7 candles for this batch
        for i in range(6, len(historical_data)):
            current_candle = historical_data[i]

            # Calculate the trading range for the previous six candles
            previous_candles = historical_data[i - 6:i]
            trading_ranges = [candle['high'] - candle['low'] for candle in previous_candles]

            # Check if the current candle has the narrowest range among the previous six
            if min(trading_ranges) == trading_ranges[-1]:
                nr7_candles.append(current_candle)

        # Move the start date for the next batch
        start_date = batch_end_date

    # Print or post detected NR7 candles for CIPLA in the entire date range
    for candle in nr7_candles:
        print(f"NR7 Candle detected at {candle['date']} for CIPLA")
else:
    print("Instrument token not found for CIPLA")

				
			

The Output does not show Cipla having NR7 Pattern. 

Why?

Because, in Buddha Scanner, We scan the price of the futures data rather than stocks data! It is quite normal that sometimes the futures data exhibit NR7 Pattern while the underlying stock does not. 

				
					NR7 Candle detected at 2023-01-19 00:00:00+05:30 for CIPLA
NR7 Candle detected at 2023-01-20 00:00:00+05:30 for CIPLA
NR7 Candle detected at 2023-02-03 00:00:00+05:30 for CIPLA
NR7 Candle detected at 2023-02-08 00:00:00+05:30 for CIPLA
NR7 Candle detected at 2023-02-17 00:00:00+05:30 for CIPLA
NR7 Candle detected at 2023-02-27 00:00:00+05:30 for CIPLA
NR7 Candle detected at 2023-03-16 00:00:00+05:30 for CIPLA
NR7 Candle detected at 2023-03-24 00:00:00+05:30 for CIPLA
NR7 Candle detected at 2023-03-29 00:00:00+05:30 for CIPLA
NR7 Candle detected at 2023-04-11 00:00:00+05:30 for CIPLA
NR7 Candle detected at 2023-04-12 00:00:00+05:30 for CIPLA
NR7 Candle detected at 2023-04-27 00:00:00+05:30 for CIPLA
NR7 Candle detected at 2023-05-12 00:00:00+05:30 for CIPLA
NR7 Candle detected at 2023-05-22 00:00:00+05:30 for CIPLA
NR7 Candle detected at 2023-05-31 00:00:00+05:30 for CIPLA
NR7 Candle detected at 2023-06-09 00:00:00+05:30 for CIPLA
NR7 Candle detected at 2023-07-26 00:00:00+05:30 for CIPLA
NR7 Candle detected at 2023-08-10 00:00:00+05:30 for CIPLA
NR7 Candle detected at 2023-08-14 00:00:00+05:30 for CIPLA
NR7 Candle detected at 2023-08-28 00:00:00+05:30 for CIPLA
NR7 Candle detected at 2023-09-08 00:00:00+05:30 for CIPLA
				
			
Post a comment

Leave a Comment

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

×Close