Python Script to Identify Hammer Candlestick Patterns in Trading Data
The Hammer candlestick forms when the open, high, and close are nearly the same, with a long lower shadow signaling a bullish rejection by buyers aiming to drive the market higher.The hammer is a reversal candlestick pattern when it occurs at the bottom of a downtrend .

Characteristics of a Hammer Candlestick:
- Shape: The hammer has a small body with a long lower shadow (at least twice the length of the body). The upper shadow is either very small or nonexistent.
- Color: The color of the hammer’s body can be either green (bullish) or red (bearish). However, a green hammer is often considered more bullish because it indicates a stronger buying pressure.
- Position in Trend: The hammer must appear after a downtrend. This is essential because the pattern is only considered a reversal signal when it follows a decline.
Interpretation:
Bullish Reversal Signal: The long lower shadow indicates that sellers pushed the price down significantly during the trading session, but strong buying pressure ultimately drove the price back up near the opening level. This suggests that buyers are starting to gain control.
Hammer Implementation in python
from kiteconnect import KiteConnect
import pandas as pd
import datetime as dt
import os
import numpy as np
cwd = os.chdir("D:\GenAi\python\python basic\Strategy")
access_token = open("access_token.txt",'r').read()
key_secret = open("api_key.txt",'r').read().split()
kite = KiteConnect(api_key=key_secret[0])
kite.set_access_token(access_token)
instrument_dump = kite.instruments("NSE")
instrument_df = pd.DataFrame(instrument_dump)
def instrumentLookup(instrument_df,symbol):
try:
return instrument_df[instrument_df.tradingsymbol==symbol].instrument_token.values[0]
except:
return -1
def fetchOHLC(ticker,interval,duration):
instrument = instrumentLookup(instrument_df,ticker)
data = pd.DataFrame(kite.historical_data(instrument,dt.date.today()-dt.timedelta(duration), dt.date.today(),interval))
data.set_index("date",inplace=True)
return data
def hammer(ohlc_df):
"""returns dataframe with hammer candle column"""
df = ohlc_df.copy()
df["hammer"] = (((df["high"] - df["low"])>3*(df["open"] - df["close"])) & \
((df["close"] - df["low"])/(.001 + df["high"] - df["low"]) > 0.6) & \
((df["open"] - df["low"])/(.001 + df["high"] - df["low"]) > 0.6)) & \
(abs(df["close"] - df["open"]) > 0.1* (df["high"] - df["low"]))
return df
ohlc = fetchOHLC("TATAMOTORS","5minute",5)
hammer_df = hammer(ohlc)
Line-by-Line Explanation
1. Importing Libraries
from kiteconnect import KiteConnect
import pandas as pd
import datetime as dt
import os
import numpy as np
- KiteConnect → Used to connect with Zerodha Kite API.
- pandas → Used to create dataframes and handle market data.
- datetime → Used to calculate date ranges for historical data.
- os → Used for file/folder path settings.
- numpy → Used for numeric operations (optional here).
2. Change Current Working Directory
cwd = os.chdir("D:\GenAi\python\python basic\Strategy")
- Changes the working folder to your strategy directory.
- So Python will look for files (access_token.txt, api_key.txt) inside this folder.
3. Generate Trading Session
access_token = open("access_token.txt",'r').read()
Opens the file access_token.txt and reads the access token (used for authenticated API calls).
key_secret = open("api_key.txt",'r').read().split()
Reads API key & secret from api_key.txt and splits into a list.
Example: ["your_api_key", "your_api_secret"]
kite = KiteConnect(api_key=key_secret[0])
Creates a KiteConnect object with your API key.
kite.set_access_token(access_token)
Sets the access token so you can call private API endpoints.
4.Get all NSE instruments
instrument_dump = kite.instruments("NSE")
- Fetches all tradable instruments from NSE exchange.
- Zerodha returns a big list of dictionaries, including instrument names, tokens, etc.
instrument_df = pd.DataFrame(instrument_dump)
- Converts that list into a pandas DataFrame for easy lookup.
5. instrument Lookup()
def instrumentLookup(instrument_df,symbol):
try:
return instrument_df[instrument_df.tradingsymbol==symbol].instrument_token.values[0]
except:
return -1
- Searches for the trading instrument by symbol (e.g., “TCS”, “INFY”).
- Returns its instrument_token, which is required for historical API.
- If symbol not found → returns -1.
6. fetchOHLC()
def fetchOHLC(ticker,interval,duration):
instrument = instrumentLookup(instrument_df,ticker)
- Gets the instrument token for the ticker.
data = pd.DataFrame(kite.historical_data(
instrument,
dt.date.today()-dt.timedelta(duration),
dt.date.today(),
interval))
- Fetches historical OHLC data using:
- instrument token
- start date (today – duration days)
- end date (today)
- interval (e.g., “5minute”, “day”)
data.set_index("date", inplace=True)
- Makes the date column the index of the DataFrame.
return data
- Returns the complete OHLC dataset.
7.Hammer() — Identify Hammer Candlestick
A hammer candle generally has:
- A small real body
- A long lower shadow
- Very small or no upper shadow
- Appears after a downtrend
def hammer(ohlc_df):
"""returns dataframe with hammer candle column"""
df = ohlc_df.copy()
df["hammer"] = (((df["high"] - df["low"])>3*(df["open"] - df["close"])) & \
((df["close"] - df["low"])/(.001 + df["high"] - df["low"]) > 0.6) & \
((df["open"] - df["low"])/(.001 + df["high"] - df["low"]) > 0.6)) & \
(abs(df["close"] - df["open"]) > 0.1* (df["high"] - df["low"]))
return df