To detect and print the last date each stock had a “Narrow Range 7 (NR7)” pattern within the specified date range, you can modify the code from the last chapter as follows.
from datetime import datetime, timedelta
# Define the date range
start_date = datetime.strptime('2023-08-01', '%Y-%m-%d')
end_date = datetime.strptime('2023-09-01', '%Y-%m-%d')
# Define the interval (in minutes)
interval = 'day'
# Iterate through the list of stock symbols
for symbol in symbol_list:
# Fetch instrument data for the current stock symbol
instruments = kite.ltp([symbol])
# Check if the stock symbol is in the instruments dictionary
if symbol in instruments:
instrument_token = instruments[symbol]['instrument_token']
if instrument_token:
# Fetch historical data for the stock
historical_data = kite.historical_data(instrument_token, start_date, end_date, interval='day')
# Initialize variables to track NR7 candles
nr7_candles = []
# Iterate through historical data to detect NR7 candles
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 (NR7)
if min(trading_ranges) == trading_ranges[-1]:
nr7_candles.append(current_candle)
# Print or post detected NR7 candles for the entire date range
for candle in nr7_candles:
print(f"NR7 Candle detected for {symbol} on {candle['date']}")
else:
print(f"Instrument token not found for {symbol}")
else:
print(f"{symbol} not found in instruments")
The output looks like –
NR7 Candle detected for NSE:NIFTY BANK on 2023-08-18 00:00:00+05:30
NR7 Candle detected for NSE:NIFTY BANK on 2023-08-21 00:00:00+05:30
NR7 Candle detected for NSE:NIFTY BANK on 2023-08-22 00:00:00+05:30
NR7 Candle detected for NSE:NIFTY BANK on 2023-08-23 00:00:00+05:30
...
...
...
...
NR7 Candle detected for NSE:TATACONSUM on 2023-08-17 00:00:00+05:30
NR7 Candle detected for NSE:NIFTY FIN SERVICE on 2023-08-18 00:00:00+05:30
NR7 Candle detected for NSE:NIFTY FIN SERVICE on 2023-08-21 00:00:00+05:30
NR7 Candle detected for NSE:NIFTY FIN SERVICE on 2023-08-30 00:00:00+05:30
Here’s an explanation of the modifications made from the NR4 Scanner to the NR7 Scanner:
min(trading_ranges)
function, and if the current candle has the narrowest range among the previous six, it is considered an NR7 candle.These changes in the NR7 Scanner enable it to specifically search for Narrow Range 7 (NR7) candles by considering the narrowest range among the previous six days and reporting the date of occurrence for each stock symbol in the symbol_list
, similar to how NR4 candles are detected in the NR4 Scanner.